1

learning how to code with Ruby and was trying learn from test first. and I stumbled something funny.

I was trying to capitalize every word but

title = 'stuart little'
a = title.split

a.each do |x|
x.capitalize
end

a.join(' ')
This one's result is 'stuart little'

but if I add the ! in capitalize

title = 'stuart little'
a = title.split

a.each do |x|
x.capitalize!
end

a.join(' ')

it ends up with the result I want which is 'Stuart Little'

just .capitalize should work shouldn't it? since I'm just capitalizing the words. and what makes .capitalize! work in this scenario?

2 Answers2

0

When a method has a ! at the end in Ruby, it is commonly referred to as a bang-method. The exclamation point indicates that the method is the dangerous version of another method.

In this case, capitalize! will modify your string, while capitalize will return a new string object. Since you are later calling on your original objects (the strings in a), your code will only work with capitalize!. To make the code work with capitalize, you would have to set that index of the array to the result of the method, e.g. a[index] = x.capitalize

Sara Fuerst
  • 5,688
  • 8
  • 43
  • 86
0

if you really want to learn I like to go to the source for map for map!. the source would tell you what the difference is

map- Invokes the given block once for each element of self.

and

map! - Invokes the given block once for each element of self, replacing the element with the value returned by the block.

MZaragoza
  • 10,108
  • 9
  • 71
  • 116