For example, I have enum.map(&:join).map(&:to_i)
. Is there a syntax in Ruby where I can write something like this: enum.map(&:join:to_i)
in order to avoid iterating through the array twice using &
operator?
Asked
Active
Viewed 32 times
1
-
Have you tested something ? – Ed de Almeida Jun 11 '17 at 03:49
-
1See @UriAgassi's answer to [this SO question](https://stackoverflow.com/questions/23695653/can-you-supply-arguments-to-the-mapmethod-syntax-in-ruby/23711606#23711606). It's a masterpiece. – Cary Swoveland Jun 11 '17 at 04:31
1 Answers
0
You could use a block (with no &
) to iterate just once:
enum.map { |e| e.join.to_i }

Gerry
- 10,337
- 3
- 31
- 40
-
that's what I actually did. Is there anything could be done like that with & operator? – Jun 11 '17 at 04:16
-
@Mikhail Oh, i see. I am not aware of any, i searched a while ago with no success. Is there a specific reason you need to use `&`? Or is a matter of style? – Gerry Jun 11 '17 at 04:21
-
@Mikhail Check [this post](https://stackoverflow.com/questions/9460204/chaining-methods-using-symbolto-proc-shorthand-in-ruby). – Gerry Jun 11 '17 at 04:24