Reputation: 7602
I am new to ruby! And i am trying to learn the use of "!" .
I am aware that ! is included to so that the user's string is modified in-place; otherwise, Ruby will create a copy of user_input and modify that instead.
But in the following case for both the programs i am getting the same output.Why?
print "Please Enter your Input"
user_input = gets.chomp
user_input.downcase!
print "Please Enter your Input"
user_input = gets.chomp
user_input.downcase
Upvotes: 1
Views: 171
Reputation: 1755
In Ruby, bangs (!) are used to inform the programmer that the method they are calling is destructive
. It's Ruby's way of saying "Hey! This method is going to change the object it is called on!". A number of safe methods in the String
, Array,
Enumerable`, etc classes have destructive counterparts.
Example:
my_str = "Hello, World!"
my_str.downcase # => "hello, world!"
my_str # => "Hello, World!"
my_str = "Goodbye, World!"
my_str.downcase! # => "goodbye, world!"
my_str #> "goodbye, world!"
As you can see, while both methods return the string's lower case variant, downcase!
actually changes my_str
permanently.
It's a very convenient aspect of Ruby that I wish more languages offered.
I think it's also worth mentioning that, because destructive methods work in-place, they are generally faster and more memory efficient than their safe counterparts who have to return new objects. Therefore, my_string.downcase!
should be preferred to my_string = my_string.downcase
whenever possible.
Upvotes: 4
Reputation: 1191
Both methods behave the same, but the returned objects are different.
downcase
returns a modified copy of user_input
. In other words, user_input
stays the same.
downcase!
returns user_input
modified. Note that this can be more memory efficient, since you don't generate a copy of user_input
.
In both cases, they return a downcase version of user_input
. That's why you have the same output.
To learn more about bang methods in Ruby, see this blog post.
hth
Upvotes: 1
Reputation: 31560
print "Please Enter your Input"
user_input = gets.chomp
user_input.downcase!
user_input
value is what the user entered, in lowercase
print "Please Enter your Input"
user_input = gets.chomp
user_input.downcase
user_input
value is what the user entered
The difference resides in the value of user_input
, not in what gets printed.
Upvotes: 1