How to get multiple values from a Array by indexes in Ruby
arrays, ruby
Solution
Yes possible. Use Array#values_at method.
Returns an array containing the elements in self corresponding to the given selector(s).The selectors may be either integer indices or ranges.
a = %w{ a b c d e f }
a.values_at(1, 3, 5) # => ["b", "d", "f"]
a.values_at(1, 3, 5, 7) # => ["b", "d", "f", nil]
Here is from your example :-
2.1.0 :001 > a = %w(a b c d e)
=> ["a", "b", "c", "d", "e"]
2.1.0 :002 > a.values_at(1,-1)
=> ["b", "e"]
2.1.0 :003 >
Problem
There is a Array `a = %w(a b c d e)`, and want to get second and last values by indexes. I can get values by `a[1], a[-1]`, but I need write `a` twice. Is there a way to get a Array by like `a.at(1, -1)`?