syntax - use of ! in Ruby -


i new ruby! , trying learn use of "!" .

i aware ! included user's string modified in-place; otherwise, ruby create copy of user_input , modify instead.

but in following case both programs getting same output.why?

print "please enter input" user_input = gets.chomp user_input.downcase!  print "please enter input" user_input = gets.chomp user_input.downcase 

in ruby, bangs (!) used inform programmer method calling destructive. it's ruby's way of saying "hey! method going change object called on!". number of safe methods in 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 can see, while both methods return string's lower case variant, downcase! changes my_str permanently.

it's convenient aspect of ruby wish more languages offered.

i think it's worth mentioning that, because destructive methods work in-place, faster , more memory efficient safe counterparts have return new objects. therefore, my_string.downcase! should preferred my_string = my_string.downcase whenever possible.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -