It "doesn't work" as you expect to do it. As capitalize applies the capitalize method on item, the receiver, and then returns a new representation of your arr_str
yielding what's inside the block. In other words and as the doc states:
map { |obj| block } → array click to toggle source
map → an_enumerator
Returns a new array with the results of running block once for every
element in enum.
Your arr_str
would be modified if you use a "persistent" method to do so, like the map's brother, Array#map!
, which works slightly different:
map! {|item| block } → ary click to toggle source
map! → Enumerator
Invokes the given block once for each element of self, replacing the element with the value returned by the block.
What your code is doing right now, is spliting the string passed, iterating over each element within the generated and stored result of split, and applying capitalize on those elements, and finally joining them and printing them with puts:
def first_upper(str)
arr_str = str.split # ["this", "is", "a", "test", "sentence"]
arr_str.map do |item|
item.capitalize
end # ["This", "Is", "A", "Test", "Sentence"]
arr_str = arr_str.join(' ') # this is a test sentence
puts arr_str # this is a test sentence
end
first_upper('this is a test sentence')
The most simple and evident approaches are:
A) To store the result of arr_str.map
in a variable to be used within the function after that step.
B) To use map! and this way modify arr_str and "persists" what's being done within that block.