Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails lists have .first and .second – is there a .hundredth or .sixty_nineth ?

Is there a class or other extension for Rails that allows more than the first few elements in a series (and the last)? These work:

[2,45,2,14,53,23,634,346,34,46,643,634,346,34,34].fifth # -> 53 [2,45,2,14,53,23,634,346,34,46,643,634,346,34,34].last # -> 34 

so where is?

list.sixth list.hundredth  
like image 294
New Alexandria Avatar asked Oct 11 '11 18:10

New Alexandria


People also ask

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

What does %w mean in rails?

%w(abc def xyz) is a shortcut for ["abc", "def","xyz"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them.


2 Answers

There was a time when Rails added these, but there was a lot of controversy so most were removed. The only remnant of this experiment is Array#forty_two:

(1..100).to_a.forty_two # => 42 
like image 177
tadman Avatar answered Oct 20 '22 14:10

tadman


You can just use square brackets:

list[6] list[100] 
like image 29
Tim Avatar answered Oct 20 '22 14:10

Tim