user1653208
user1653208

Reputation: 35

Get single element from Ruby range

I'm trying to print a single element from an array of 500 numbers. I initialized it using

arr = (1..500)

I can print from for loops:

for n in arr
  print n +"\n"
end

I can print using arr.each, but if I try to just grab one element I get an error.

print arr[0]
>undefined method `[]' for 1..500:Range (NoMethodError)

If I initialize an array arr2 = ["a", "b", "c"] and try to grab a single element that way it works fine.

I am assuming it is because of the way I initialized it (using the range) but eveywhere I look they say that is how you should initialize an array of numbers.

Is there any way for me to get a single element from my array?

Upvotes: 1

Views: 333

Answers (2)

Alexey918331
Alexey918331

Reputation: 1

Here is how to do it without converting the whole thing into array.

class Range
  def index(n)
    return nil unless n < self.size
    self.each_with_index { |x, i| return x if i == n }
  end
end

range = 0..100000000000
range.index(120) # => 120

Upvotes: 0

d11wtq
d11wtq

Reputation: 35298

That's not a Array, it's a Range. You can convert it to an Array using to_a:

range = 0..500
arr   = range.to_a

puts arr[7] # => 6

Upvotes: 5

Related Questions