old_dog_new_tricks
old_dog_new_tricks

Reputation: 5

How to reference objects in an array created with .select method?

As I understand it, running a .select method on an array generates a new array. My question is how to reference that new array?

So when I have something like this:

Num = [3, 5, 7, 9, 11, 13, 15, 17, 19]
x = rand(1..10)
Num.select { |i| i > x}

I want to reference specific objects in the new array generated by this .select.

For example, I'd like to say

puts new_array[0]

Or something similar. But since the new array doesn't have a "name," I don't know how to call the objects in it.

Thanks for any help!

Upvotes: 0

Views: 115

Answers (1)

kcdragon
kcdragon

Reputation: 1733

You assign a local variable to the result of the select.

num = [3, 5, 7, 9, 11, 13, 15, 17, 19]
x = rand(1..10)
new_array = num.select { |i| i > x}
puts new_array[0]

I also changed your variable Num to num. Usually, only classes are named with the first letter capitalized and the rest lowercase.

Upvotes: 4

Related Questions