开发者

Ruby: implicit block iterator

开发者 https://www.devze.com 2023-04-11 06:54 出处:网络
Is there a way to do this? instead of: links.each do |link| link.color \"red\" end make th开发者_Go百科e iterator (between | |) implicit like so:

Is there a way to do this? instead of:

links.each do |link|
  link.color "red"
end

make th开发者_Go百科e iterator (between | |) implicit like so:

links.each do
  color "red"
end


I am pretty sure that this is not possible. You can however instance_eval each element, but I certainly wouldn't recommend it without good reason

foo = ["test","test2","foo","bar","foobar"]

foo.each do |f|
  f.instance_eval do
    p reverse
  end
end


I'm not sure this is worth the effort in this instance (and it adds unnecessary complexity) but it's nice to know that you can do something like the following:

proc = Proc.new { |i| i.color 'red' }
links.map(&proc)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号