Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 612
themirror Avatar asked Jan 28 '26 05:01

themirror


2 Answers

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
like image 66
Gazler Avatar answered Jan 30 '26 21:01

Gazler


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)
like image 28
jodell Avatar answered Jan 30 '26 21:01

jodell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!