Ruby gets the nth item from an array

Suppose I have this range:

("aaaaa".."zzzzz")

How can I get the Nth element from a range without generating the whole thing in front of the hand / every time?

+5
source share
2 answers

List only to n,

or

Design a function that sets the number n, f (n) gives you the nth element of your range of possible solutions.

26. - . , -10 26 ( ) ( ). , .

, , : D

ruby ​​ n- :

def rbase(value)
  a = ('a'..'z')
  b = a.to_a
  base = b.length
  text = []
  begin 
    value, rest = value.divmod(base)
    text << b[rest]
  end until value.zero?
  text.reverse.join
end

.

irb(main):030:0> rbase(789).rjust(10,'a')
=> "aaaaaaabej"
+1

:

("aaaaa".."zzzzz").first(42).last  # ==> "aaabp"

- , N , - :

module Enumerable
  def skip(n)
    return to_enum :skip, n unless block_given?
    each_with_index do |item, index|
      yield item unless index < n
    end
    self
  end
end

("aaaaa".."zzzzz").skip(41).first # ==> "aaabp"

. , , Enumerable, ( ). Ruby 1.8.7+, require "backports"

+8

All Articles