What is the difference between downcase and downcase!

3

I'm starting with Ruby and I came across the following code:

 user_input = gets.chomp
 user_input.donwcase!

My question is why to use the exclamation point after the downcase.

    
asked by anonymous 16.04.2014 / 15:33

1 answer

9

Ruby exclamation points are used to denote "dangerous" methods. In the case of the downcase! method it modifies the object itself. Another notable example is exit (which gives chance for the application to finish normally and execute the at_exit method) vs. exit! (immediate termination).

The "safe" version of the downcase method returns a modified copy of string without changing its contents:

foo = "UMA STRING" 
bar = foo.downcase
puts foo            # UMA STRING
puts bar            # uma string

The exclamation point version is used to change string :

foo = "UMA STRING"
foo.downcase!
puts foo            # uma string   

Source : SOE - Why are exclamation marks used in Ruby methods?

    
16.04.2014 / 15:41