This also works:
b = "word1 word2"
((a,b)) = b.scan(/^(\w+)\s(\w+)$/)
p a => "word1"
p b => "word2"
The outer parens matches the outer array, and the inner parens matches the inner array, allowing a and b to decompose it.
It's a pretty useful trick when decomposing nested arrays.
Ken
Vincent Fourmond wrote:
···
Luca Scaljery wrote:
Hi All
I tried to put an array into variables like this
b = "aaa bbb"
s, h = b.scan(/^(\w+)\s(\w+)$/)
But for some reason 's' becomes an array and 'h' is undefined!!
The problem is that scan returns an array of arrays:
[ # first match:
[ #first group :
"aaa",
# second group:
"bbb"
]
]
So you might want in your case:
s, h = b.scan(/^(\w+)\s(\w+)$/)[0]
s, h = b.scan(/^(\w+)\s(\w+)$/).flatten
This also works:
b = "word1 word2"
((a,b)) = b.scan(/^(\w+)\s(\w+)$/)
p a => "word1"
p b => "word2"
The outer parens matches the outer array, and the inner parens matches
the inner array, allowing a and b to decompose it.
It's a pretty useful trick when decomposing nested arrays.
Ken
Seems like the long way around...
foo = ["one", "two"]
a, b = foo
a #=> "one"
b #=> "two"
This also works:
b = "word1 word2"
((a,b)) = b.scan(/^(\w+)\s(\w+)$/)
p a => "word1"
p b => "word2"
The outer parens matches the outer array, and the inner parens matches
the inner array, allowing a and b to decompose it.
It's a pretty useful trick when decomposing nested arrays.
Ken
Seems like the long way around...
foo = ["one", "two"]
a, b = foo
a #=> "one"
b #=> "two"
Actually, to be more clear
foo = "hello world"
a,b = foo.split
a #=> "hello"
b #=> "world"