I’m trying to write a function that would apply the function to just one item if it’s not a collection, or else apply that function to each of the collections elements. For example:
replace spaces with underscores
foo 'a bear' => 'a_bear'
foo ['a bear', 'a bee'] => ['a_bear', 'a_bee']
Is this possible?
It depends on how you define “collection”. The most natural option would probably be either “any Enumerable” or even “anything with an each method”. However this leads to a problem because Strings are Enumerable, too – in ruby 1.8, at least.
If you only need it to work with arrays, it’s easy: