I use send
like this:
[:last, :first].map { |sym| [0,1,2].send(sym) }
#=> [2, 0]
I am trying to pass to send
a symbol of index and rindex, and a closure for their execution:
[:rindex, :index].map { |sym| [0,1,2].send(sym, { |x| x %2 == 0 }) }
I get an error message:
SyntaxError: (irb):4: syntax error, unexpected '|', expecting '}'
...p { |sym| [0,1,2].send(sym, { |x| x %2 == 0 }) }
What am I doing wrong?
What am I doing wrong?
In Ruby, blocks are being passed after the argument list instead of inside it:
foo(1, { puts 'Hello' }) # wrong
foo(1) { puts 'Hello' } # right
So, your code should look like:
[:rindex, :index].map {|sym| [0, 1, 2].send(sym) {|x| x %2 == 0 }}
Note: you should always prefer public_send
over send
. send
does two things at once: allow the name of the message to be dynamic, and break encapsulation. If you use send
, people who read your code are never quite sure which of the two features you are actually using. In this case, you are not breaking encapsulation at all, you are only using the dynamic message name. That's exactly what public_send
does.
%i[rindex index].map {|meth| [0, 1, 2].public_send(meth, &:even?)}
This would be a more idiomatic way to write your code.