简体   繁体   中英

Calling custom method with &: syntax om Ruby

So basically I was looking at this simple example:

%w[A B C].map(&:downcase)

And got interested in the &: syntax. After reading some articles I think I got the point (or at least I think so) so I've decided to implement something similar for Integer like this:

class Integer
  def my_multiplier
    puts "66"
  end
end

And here I can get advantage of the &: syntax cause I am allowed to do so:

3.times(&:my_multiplier)

But of course the result is three times the number 66 .

My questions is how to refactor my method so I can actually use the values from 3.times.. ?

First of all, the syntax is &object , not &: . &object calls .to_proc on the object.

Now, assuming you'd like your multiplier to simply puts your integer multiplied by 66, you'd write it as:

class Integer
  def my_multiplier
    puts 66 * self
  end
end

Which will result in

2.5.1 :006 > 3.times(&:my_multiplier)
0
66
132

This is the equivalent of calling

3.times { |i| i.my_multiplier }

You can also define your my_multiplier as a proc or a lambda,

2.5.1 :001 > p = ->(i) { puts i * 66 }
 => #<Proc:0x00005582b3ae5638@(irb):1 (lambda)> 
2.5.1 :002 > 3.times(&p)
0
66
132

It's unclear what you were shooting for with that method, but current integer will be available as self . So you can do something like this:

class Integer
  def double 
    self * 2
  end 

end

3.times.map(&:double) # => [0, 2, 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM