Created
October 24, 2015 12:15
-
-
Save ibanez270dx/9a6dd2be0a4eacec1af1 to your computer and use it in GitHub Desktop.
use splat with an array when case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# if we want to check whether a particular value is in an array, we have | |
# a couple options... Most times simply calling array.include?(element) is | |
# sufficient, but we can also get creative by using the splat function | |
# with a case statement to check multiple arrays ;) | |
hondai = ['hondai', 'acura', 'civic', 'element', 'fit', ...] | |
toyota = ['toyota', 'lexus', 'tercel', 'rx', 'yaris', ...] | |
case car | |
when *toyota then # Do something for Toyota cars | |
when *hondai then # Do something for Hondai cars | |
... | |
end | |
# ...which translates to: | |
case car | |
when 'toyota', 'lexus', 'tercel', 'rx', 'yaris', ... then # Do something for Toyota cars | |
when 'hondai', 'acura', 'civic', 'element', 'fit', ... then # Do something for Hondai cars | |
... | |
end | |
# ...which is identical to: | |
case | |
when toyota.include?(car) then # Do something for Toyota cars | |
when hondai.include?(car) then # Do something for Hondai cars | |
... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment