ruby

Can you use Ruby's block shorthand to call a method like the array accessor?


I'm used to being able to shorten

some_array.map { |e| e.to_s }

to

some_array.map(&:to_s)

Is there a way to shorten

some_array_of_arrays.map { |e| e[4] }

similar to

some_array_of_arrays.map(&:[4])

Obviously I've tried that last example but it doesn't work. Ideally the solution would be generalized to other 'weirdly formatted' method calls like [].

I am not interested in any Rails/ActiveSupport solution. Plain Ruby only, assuming there is some sort of solution.


Solution

  • you can use Proc:

    > a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14]]
    > third_elem = Proc.new {|x| x[2]}
    > a.map(&third_elem)
    #> [3, 7, 11, nil] 
    

    OR

    > a.map &->(s) {s[2]}
    #=> [3, 7, 11, nil]