Test array and assign result to variable


#1

I have this example:
class Array
def find
for i in 0…size
value = self[i]
return value if yield(value)
end
return nil
end
end
x = [1, 3, 5, 7, 9]
x.find {|v| vv > 30 }
It says that return 7 - the first value wich match the condition
I run it in NetBeans but don’t see the output
I tried this:
x.find {|v|
if v
v > 30
puts v
end } but now prints the both values that match the condition: 7, 9
So the problem is how can I see only the first match, and most important
how can I extract this value to a variable to use it somewhere else.
Because in general I want to test an array for a condition, and then use
the results
Thanks


#2

Adrian A. removed_email_address@domain.invalid wrote:

x = [1, 3, 5, 7, 9]
x.find {|v| v*v > 30 }
It says that return 7 - the first value wich match the condition
I run it in NetBeans but don’t see the output

Because you didn’t ask for any output. It would suffice to change the
last line from

x.find {|v| v*v > 30 }

to

puts x.find {|v| v*v > 30 }

I tried this:
x.find {|v|
if v*v > 30
puts v
end } but now prints the both values that match the condition: 7, 9
So the problem is how can I see only the first match, and most important
how can I extract this value to a variable to use it somewhere else.
Because in general I want to test an array for a condition, and then use
the results

It’s good that you’re trying to “roll your own” on this, but still,
Array#find already exists and does exactly what you’re looking for.

m.


#3

Thank you,
it works. I have complicated myself!
But how I retain this result in a variable to work with it.
Because I think that must be situations in wich you put results from
some calculations in an array, and then due tu a condition, you want to
take that specific value to work further with it
Adrian


#4

I respond to myself.
Of corse the answer is
x = [1, 3, 5, 7, 9]
y = x.find {|v| vv > 30 } #and now I have the variable
puts y => 7
Sorry, I am a very beginer and I was iduced in error because in the
book the ex was [1, 3, 5, 7, 9].find {|v| v
v > 30 } and it didn’t came
to me to write puts before such a expresion, and I worked on v.
Thanks again
Adrian