For a long time I tried desperately to get this to work, I’ve googled, I’ve tinkered, and I’ve asked some local Rubyists (though not pdx.rb, though I really should).
We were trying to do something like this at work:
case user.roles.included? (... magic ...)
when ['admin', 'editor']
then ...
when ['anonymous']
then ...
end
So you can see how it feels like a case, but because it’s not using === as El noted, it doesn’t work. I know I can use if but it feels like a place where a case should be used.
whenuses the===operator to compare the value given tocaseagainst the argument given towhen. Alsothenis unnecessary when appearing on a different line from thewhenstatement The correct code for what you’re trying to do is:As for the new addition to the question:
This doesn’t work because Array’s
===doesn’t map toinclude. I’m not sure where Array’s===operator comes from or even what it does, but you could override it to provide the functionality you want.Judging by the above code you want the
caseto trigger if one of the users roles matches the array. This will overrideArray#===to do just that:Caveat: Depending on where you override
Array#===this can have unforeseen consequences, as it will change all arrays in that scope. Given that===is being inherited from Object where it is an alias for==, I’m not expecting it to be a big problem.Places where the new
===differs from the old===:===will return true if either array is a subset or reordering of the other.===will only return true if the two arrays are identical (order and contents).So far as I know,
case/whenis the only time===could be implicitly called on an array.