If you wanted to split a space-separated list of words, you would use
def words(text)
return text.split.map{|word| word.downcase}
end
similarly to Python's list comprehension:
words("get out of here")
which returns ["get", "out", "of", "here"]
. How can I apply a block to every character in a string?
Just like many other programming languages, the Map method is also in ruby. You use a ruby map or map, in general, to transform the data and perform functions on each element of the object. You can use it with the hashes, ranges, and arrays. All these work as an Enumerable object with a map.
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
The map() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum. The object is repeated every time for each enum. In case no object is given, it return nil for each enum.
Use String#chars
:
irb> "asdf".chars.map { |ch| ch.upcase }
=> ["A", "S", "D", "F"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With