7

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)?

1
  • 3
    Did you look at the documentation for Array? Your answer is there. Commented Jun 2, 2014 at 12:50

1 Answer 1

16

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 > 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.