Forum: Ruby Test array and assign result to variable

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Adrian C. (Guest)
on 2009-06-05 20:22
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
matt neuburg (Guest)
on 2009-06-05 21:05
(Received via mailing list)
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.
Adrian C. (Guest)
on 2009-06-06 02:40
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
Adrian C. (Guest)
on 2009-06-06 03:59
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
This topic is locked and can not be replied to.