30

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 
New Alexandria
  • 6,951
  • 4
  • 57
  • 77
  • Is it possible to access this on a collection of objects, like `Client.where( active: true ).second`? – Joshua Pinter Sep 01 '14 at 17:24
  • @JoshPinter it should be, given that [ActiveRecord collections are naturally Array class, but mimic being something else](http://stackoverflow.com/questions/14065425/why-are-rails-model-association-results-not-naturally-activerecordrelations). The link here is to a discussion I had on the same issue. – New Alexandria Sep 01 '14 at 18:22
  • 1
    Yup, after giving it a quick try, this does indeed work. What **doesn't** work is `Client.second` or `Client.third`. Acting directly on the Class, only `Client.first` and `Client.last` work. Cheers. – Joshua Pinter Sep 01 '14 at 18:53

3 Answers3

70

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
tadman
  • 208,517
  • 23
  • 234
  • 262
17

You can just use square brackets:

list[6]
list[100]
Tim
  • 14,447
  • 6
  • 40
  • 63
5

In activesupport, it does monkey patching few of these methods into Array class. If you really want more, you can take a look how to implement from activesupport:

https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/array/access.rb

Samnang
  • 5,536
  • 6
  • 35
  • 47