I would like to know what the difference is between these two examples:
my_name = gets.chomp
my_name.capitalize
and
my_name = gets.chomp
my_name.capitalize!
I would like to know what the difference is between these two examples:
my_name = gets.chomp
my_name.capitalize
and
my_name = gets.chomp
my_name.capitalize!
The difference is
my_name.capitalize
returns a capitalized version of my_name
without affecting the object my_name
points to, while
my_name.capitalize!
still returns a capitalized version of my_name
but my_name
is changed too, so
my_name = "john"
puts my_name.capitalize # print 'John' but the value of my_name is 'john'
puts my_name.capitalize! # print 'John' and now the value of my_name is 'John'
From the Ruby capitalize
docs:
capitalize
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
capitalize!
Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made.
I'm always so happy to see somebody getting into ruby!
The thing with ruby is that, even though it's a very friendly language, it assumes a lot of things without necessarily telling the newbies about it. They make lots of sense once you have a couple months under the belt with the language, but not before, so I understand your question.
First of all, the bang (!) is just part of the name itself. Ruby allows exclamation points and question marks as part of the method name just as any other character. Cool, right?
Why do people bother, though? Well, it's a convention. As a rule of thumb, an accepted explanation of why a method should have a bang sign is that the method does an invasive, destructive or mutating thing, that is, it destroys data, runs a transaction on the database, permanently changes data, etc.
It's not obligatory to name these kinds of methods like this, but it's a convention that's very well withheld in the Ruby community.
Programming Ruby says:
Methods that are "dangerous," or modify the receiver, might be named with a trailing "!".
Hope this answers your question.