irb(main):010:0* x = "hello world baby girl"
=> "hello world baby girl"
irb(main):011:0>
irb(main):012:0*
irb(main):013:0* x.grep(/hello/)
NoMethodError: undefined method `grep' for "hello world baby girl":String
from (irb):13
from /usr/bin/irb:12:in `<main>'
It was on Ruby 1.8-Strings, but only because they were belonging to the group of objects that mixed in Enumerable.
There, grep behaves like this (line by line):
x = "hello world baby girl"
x.grep(/hello/)
#=> ["hello world baby girl"]
x = "hello\nworld\nbaby\ngirl"
x.grep(/hello/)
#=> ["hello\n"]
The same can be done in Ruby 1.9 by just splitting the String beforehand. Arrays are Enumerable and thus
still have grep:
x = "hello\nworld\nbaby\ngirl"
x.split("\n").grep(/hello/)
#=> ["hello"]
Note the absence of the line-break which might be intended or not :).
Regards,
Florian Gilcher
···
On Nov 27, 2009, at 11:26 PM, Ruby Newbee wrote:
Hello,
I tried to grep from a string, but got wrong.
irb(main):010:0* x = "hello world baby girl"
=> "hello world baby girl"
irb(main):011:0>
irb(main):012:0*
irb(main):013:0* x.grep(/hello/)
NoMethodError: undefined method `grep' for "hello world baby girl":String
from (irb):13
from /usr/bin/irb:12:in `<main>'
Thanks, that sounds be more reasonable, b/c I like to grep from an
array not a string (yes perl does this).
btw, why 0/0 got failed but 0.0/0.0 seems valid?
irb(main):144:0> v=0/0
ZeroDivisionError: divided by 0
from (irb):144:in `/'
from (irb):144
from /usr/bin/irb:12:in `<main>'
irb(main):145:0> v=0.0/0.0
=> NaN
It's the difference betweeen floating point and integer arithmetic.
When working with integers all results must be valid integers, whereas
floating point can represent NaN (Not a Number), negative zero,
and infinity and negative infinity:
Stupid me, of course! Thanks for the quick enlightenment. I somehow had assumed the text the OP was ultimately interested in was that matched by the expression. But that assumption is not covered by the posting.
Cheers
robert
···
On 11/28/2009 05:35 PM, Rick DeNatale wrote:
On Sat, Nov 28, 2009 at 11:10 AM, Robert Klemme > <shortcutter@googlemail.com> wrote: