LoginSignup
1
0

More than 3 years have passed since last update.

m(&->(x,y){x}) が 0 で m(&->(x,y){x*y}) が 1 だと

Last updated at Posted at 2020-01-29

Ruby の問題です。下記の記事の続編ですが,少し難しくなっています。
m{|x| x } が 0 で m{|x, y| x * y } が 1 だと? - Qiita

以下のテストをパスするメソッド m を定義せよ。

require "test/unit"

class T < Test::Unit::TestCase
  test "" do
    assert_equal 0, m(&->(x, y){ x })
    assert_equal 1, m(&->(x, y){ x * y })
  end
end

答えはここをめくってね

Ruby 2.7 以降:

def m
  yield 0, "".tap{ def _1.coerce(*); [1, 1]; end }
end

Ruby 2.6 まで:

def m
  yield 0, "".tap{ |o| def o.coerce(*); [1, 1]; end }
end

などとする。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0