[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Test array and assign result to variable

Adrian Arlechin

6/5/2009 4:22:00 PM

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| 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
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
--
Posted via http://www.ruby-....

3 Answers

matt

6/5/2009 5:02:00 PM

0

Adrian Arlechin <adrian.cinta@gmail.com> wrote:

> 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| 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.


--
matt neuburg, phd = matt@tidbits.com, http://www.tidbits...
Leopard - http://www.takecontrolbooks.com/leopard-custom...
AppleScript - http://www.amazon.com/gp/product/...
Read TidBITS! It's free and smart. http://www.t...

Adrian Arlechin

6/5/2009 10:40:00 PM

0

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
--
Posted via http://www.ruby-....

Adrian Arlechin

6/6/2009

0

I respond to myself.
Of corse the answer is
x = [1, 3, 5, 7, 9]
y = x.find {|v| v*v > 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

--
Posted via http://www.ruby-....