slice returning multiple values

J

Joel VanderWerf

Fantasy for the day...

str = "foo bar"
x, y = str[/(foo) (bar)/, 1, 2]

x # ==> "foo"
y # ==> "bar"

Oh, well, there is always this:

(x, y), = str.scan(/(foo) (bar)/)
 
R

Robert Klemme

Joel VanderWerf said:
Fantasy for the day...

str = "foo bar"
x, y = str[/(foo) (bar)/, 1, 2]

x # ==> "foo"
y # ==> "bar"

Oh, well, there is always this:

(x, y), = str.scan(/(foo) (bar)/)

irb(main):007:0> x, y = str.match(/(foo) (bar)/).to_a[1..2]
=> ["foo", "bar"]

irb(main):010:0> x, y = str.split /\s+/
=> ["foo", "bar"]
irb(main):011:0> x
=> "foo"
irb(main):012:0> y
=> "bar"
irb(main):013:0>

irb(main):013:0> x, y = str.scan /\w+/
=> ["foo", "bar"]

irb(main):018:0> x, y, rest = str.split( /\s+/, 3 )
=> ["foo", "bar"]
irb(main):019:0> rest
=> nil

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top