Case ... when and arrays (or what was why_ showing us at rai

Hi,

I would like to test a string foo against an array bar in as case…
when clause and would like to know the best way to do this. I am sure
why_ did something neat with an * operator, but can’t find any
reference. I could do it long hand, but that just aint rubyish.

e.g.

foo = “that”
bar = %(this that other)
case foo

when (some clever way of test for foo in the array bar)
.
.
else

end

Anybody got a good suggestion?

J2M wrote:

bar = %(this that other)
You don’t have an array in bar, just a string. You need to use %w:

bar = %w(this that other)

case foo

when (some clever way of test for foo in the array bar)

when *bar

which corresponds to:

when “this”, “that”, “other”

.
.
else

end

Anybody got a good suggestion?

Cheers,
Robin

On 10/11/06, J2M [email protected] wrote:

bar = %(this that other)
case foo

when (some clever way of test for foo in the array bar)
.
.
else

end

Anybody got a good suggestion?

when *bar

http://redhanded.hobix.com/bits/wonderOfTheWhenBeFlat.html

On 10/11/06, Drew O. [email protected] wrote:

If you just want to check if the array contains that string somewhere,
can you just use:

if foo =~ array.join(" ")
blah
else
blah2
end

Ah, but consider:

array = [ “foo”, “bar”, “baz” ]
foo = “foo bar”
puts(foo =~ array.join(" ") ? “true” : “false”)
puts(array.include?(foo) ? “true” : “false”)
puts case foo
when *array: “true”
else “false”
end

produces:

true
false
false

The semantics are different. Your approach may be valid in some cases,
I’m not discounting it altogether, but the two approaches do yield
different results in the edge cases.

Jacob F.

%(…) was over eagre typing on my part.

Damn I am sure I tried when *bar 2 hours ago!

Thanks for the answer Robin.

I like that so much I want more…

Can you do something equivalent with an if and *bang?

If you just want to check if the array contains that string somewhere,
can you just use:

if foo =~ array.join(" ")
blah
else
blah2
end

Cool thanks Ken, I hadn’t really played with grep at all, that and
*bang have just halved the code I am writing.

To determine if some object is included in a collection:

collection.include? obj

e.g.:

%w(foo bar baz).include? "foo"
=> true

also, have a look at Enumerable#grep – it uses === for comparison
(just like case/when):

a = [ "bar", 3, 7.5, "baz" ]

a.grep String
=> ["bar", "baz"]

a.grep Numeric
=> [3, 7.5]

a.grep /^b/
=> ["bar", "baz"]

a.grep "bar"
=> ["bar"]

a.grep 1..5
=> 3

-Ken

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs