What’s the difference between downcase and downcase!

Asked

Viewed 296 times

5

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

 user_input = gets.chomp
 user_input.donwcase!

My question is why I use the exclamation mark after the downcase.

  • I believe you can find the answer here: http://stackoverflow.com/questions/709229/difference-between-downcase-and-downcase-in-ruby

2 answers

10


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

The "safe" version of the method downcase back a modified copy of string without altering the content of the:

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

The exclamation mark version is used to change the exclamation mark itself string:

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

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

1

In the standard Ruby standart library, the Bang (!) means that it does not modify the variable that is calling the method.

But there are other implementations for it, for example, in Active Record the Bang is used to symbolize that the method will throw an exception instead of returning a simple false. Source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.