Star in case statements

I just noticed something that I either didn’t know
or just forgot. :slight_smile:

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

···


Hal Fulton
hal9000@hypermetrics.com

Ditto, I just noticed something that I didn’t know while trying to
simplify some of my code: a negative bit shifting is the equivalent of a
shifting of the same amount of bits, but in the other direction.

Example:

4 << -1
=> 2
2 >> -1
=> 4

I like it, saves me a couple of lines and makes my code clearer.

···

Hal E. Fulton hal9000@hypermetrics.com wrote:

I just noticed something that I either didn’t know
or just forgot. :slight_smile:


Luc Heinrich - lucsky@mac.com

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

martin

···

Hal E. Fulton hal9000@hypermetrics.com wrote:

I just noticed something that I either didn’t know
or just forgot. :slight_smile:

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

(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

···

Dave Brown dagbrown@lart.ca wrote:

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.