My favorite Ruby thing this week: when *my_array

This week we added a feature where our texting club customers can define their own aliases for the JOIN keyword, so they can track and measure which advertising is attracting people to JOIN. (For example a receipt might say “Text JOIN to…” while a sign in a bus might say “Text SNOWBUNNY to ….”)

In Ruby, the basic use of case / when is something like:

case keyword
when "KEYWORD1"
  # do something
when "KEYWORD2"
  # do something else
end

In this case, the when needs to evaluate run-time data, not compile-time data. In Ruby it is trivially simply to implement run-time comparison arguments for a case – when statement by using an array name as the argument to the when clause.

The solution with Ruby is trivially simple: use when *array_name

join_aliases = ("JOIN " + myaccount.join_aliases.to_s).split(" ")
  # sets join_aliases = ["JOIN", "SNOWBUNNY", "SNOW"]
case keyword
when *join_aliases
  # do JOIN stuff

Leave a Reply

Your email address will not be published. Required fields are marked *