简体   繁体   中英

Ruby: implicit block iterator

Is there a way to do this? instead of:

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

make the 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)

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