Last active
July 7, 2017 21:22
-
-
Save ckib16/8594ee4f8826c0f06b6dfd7ce30dc99e to your computer and use it in GitHub Desktop.
Mutating arguments - clarifications from written test.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From LaunchSchool written test 2017-07-07 | |
def shout(string) | |
string + "!!!" # => "hello world!!!" # Just an operation, not a method on `string`. Silimar to `1 + 1`. Argument `string` stays coupled to `sentence` | |
string.upcase! # => "HELLO WORLD" # Mutates the caller | |
end # => :shout | |
sentence = "hello world" # => "hello world" | |
shout(sentence) # => "HELLO WORLD" | |
puts sentence # => nil | |
########################### | |
def shout(string) | |
string += "!!!" # => "hello world!!!" # Non-mutating method, shorthand for `string = string + '!!!'`. Saves to new memory address & decouples `string` from `sentence`. ` | |
string.upcase! # => "HELLO WORLD!!!" # Already decoupled (above), so `string` does not affect `sentence` | |
end # => :shout | |
sentence = "hello world" # => "hello world" | |
shout(sentence) # => "HELLO WORLD!!!" | |
puts sentence # => nil | |
############################ | |
def shout(string) | |
string << "!!!" # => "hello world!!!" # Mutates the caller (argument `string` stays coupled to `sentence`) | |
string.upcase! # => "HELLO WORLD!!!" # Mutates the caller again (argument `string` stays coupled to `sentence`) | |
end # => :shout | |
sentence = "hello world" # => "hello world" | |
shout(sentence) # => "HELLO WORLD!!!" | |
puts sentence # => nil | |
# >> HELLO WORLD | |
# >> hello world | |
# >> HELLO WORLD!!! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment