-1

Is there a way to use the array being acted upon inside of a method, like how in javascript you can send a copy of that array to the callback?

so something like:

array.something.somethingelse.anotherthing do |element|

    #i want to be able to use array.something.somethingelse here without 
    #having to call something and somethingelse on the original array again

end
jjames
  • 93
  • 1
  • 1
  • 7

1 Answers1

3

It's highly irregular, but you can always do this:

array.something.somethingelse.tap do |se|
  se.anotherthing do |element|
  end    
end

Normally you'd create an intermediate variable:

se = array.something.somethingelse

se.anotherthing do |element|
end

There's no real advantage to the tap approach, it doesn't make the code more readable.

In all honesty the best approach is to delegate this to a function like:

do_another_thing(array.something.somethingelse)

And then there you have a free variable by virtue of it being the argument:

def do_another_thing(se)
  se.anotherthing do |element|
  end
end
tadman
  • 208,517
  • 23
  • 234
  • 262