I DID checkout both this question, and that other similar question, none of them offers a solution to replace elements of an array with multiple test values.
I have a Ruby array:
array = ["america", "europe", "asia", "africa", "france", "usa", "spain", "paris", "los angeles"]
I would like to transform this array, to get the following result:
array = ["continent", "continent", "continent", "continent", "country", "country", "country", "city", "city"]
My first attempt was to do something like that:
array.collect! do |element|
(element == "america") ? "continent" : element
(element == "europe") ? "continent" : element
(element == "asia") ? "continent" : element
(element == "africa") ? "continent" : element
(element == "france") ? "country" : element
(element == "usa") ? "country" : element
(element == "spain") ? "country" : element
(element == "paris") ? "city" : element
(element == "los angeles") ? "city" : element
end
I have two problems with this code:
I am not sure this is the way to use a Ruby
block
withdo
end
.This code is not
DRY
and I believe I could use a set of threecase
loops instead, one for continents, one for countries and one for cities.