Star in case statements

H

Hal E. Fulton

I just noticed something that I either didn't know
or just forgot. :)

You can use the *array notation to specify values
for the when clause in a case statement:

list1 = [1,2,6,8,9]
list2 = [3,4,5,7,10]
case item
when *list1
puts "in list 1"
when *list2
puts "in list 2"
end

Cool, eh?

Hal
 
M

Martin DeMello

Hal E. Fulton said:
I just noticed something that I either didn't know
or just forgot. :)

You can use the *array notation to specify values
for the when clause in a case statement:

Very neat! I was gratified when I first discovered you could splat a
range too (as in a = *(1..10)).

martin
 
D

Dave Brown

: > I just noticed something that I either didn't know
: > or just forgot. :)
: >
: > You can use the *array notation to specify values
: > for the when clause in a case statement:
:
: Very neat! I was gratified when I first discovered you could splat a
: range too (as in a = *(1..10)).

This is weird though:

irb(main):001:0> *(1..10)
SyntaxError: compile error
(irb):1: syntax error
from (irb):1
irb(main):002:0> a=*(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb(main):003:0>

I wonder why that does that.

--Dave
 
M

Martin DeMello

Dave Brown said:
This is weird though:

irb(main):001:0> *(1..10)
SyntaxError: compile error
(irb):1: syntax error
from (irb):1
irb(main):002:0> a=*(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb(main):003:0>

I wonder why that does that.

*(1..10) doesn't expand to [1,2,3,4,5,6,7,8,9,10], it expands to
1,2,3,4,5,6,7,8,9,10. a = 1,2,3,4,5,6,7,8,9,10 does the right thing (see
the multiple assignment section of the pickaxe book). [*(1..10)] works
too.

martin
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top