0

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!

2
  • 2
    new_array = Num.select {|i| i > x} then new_array[0] etc. Commented Aug 27, 2016 at 22:48
  • So obvious. Thank you. I had tried new_array = [] new_array << Num.select { |i| i > x} but that added an array within an array. This is so simple. Thanks again. Commented Aug 27, 2016 at 22:58

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.