Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Ruby equivalent of map() for strings?

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?

like image 688
EMBLEM Avatar asked Mar 22 '14 23:03

EMBLEM


People also ask

Can you use map on string Ruby?

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.

Is there a map in Ruby?

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.

What is the map method in Ruby?

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.


1 Answers

Use String#chars:

irb> "asdf".chars.map { |ch| ch.upcase }
  => ["A", "S", "D", "F"]
like image 164
Paige Ruten Avatar answered Oct 04 '22 14:10

Paige Ruten