Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple values from a Array by indexes in Ruby

Tags:

arrays

ruby

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

like image 471
ironsand Avatar asked Jun 02 '14 12:06

ironsand


1 Answers

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 > 
like image 117
Arup Rakshit Avatar answered Sep 28 '22 07:09

Arup Rakshit