[英]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: 阅读一些文章后,我认为我明白了(或者至少是这样),所以我决定为
Integer
实施类似的操作:
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
. 但是结果当然是数字
66
三倍。
My questions is how to refactor my method so I can actually use the values from 3.times..
? 我的问题是如何重构我的方法,以便实际上可以使用
3.times..
的值?
First of all, the syntax is &object
, not &:
. 首先,语法是
&object
,不是&:
&object
calls .to_proc
on the object. &object
在&object
调用.to_proc
。
Now, assuming you'd like your multiplier to simply puts your integer multiplied by 66, you'd write it as: 现在,假设您希望乘数简单地将整数乘以66,则将其写为:
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, 您还可以将
my_multiplier
定义为proc或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
. 不清楚您使用该方法的目的是什么,但是当前整数将作为
self
。 So you can do something like this: 因此,您可以执行以下操作:
class Integer
def double
self * 2
end
end
3.times.map(&:double) # => [0, 2, 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.