Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Created April 19, 2020 00:39
Show Gist options
  • Save harrisonmalone/d4c04ade3f103d06bd3c4f56bcbbdd62 to your computer and use it in GitHub Desktop.
Save harrisonmalone/d4c04ade3f103d06bd3c4f56bcbbdd62 to your computer and use it in GitHub Desktop.
class Account
attr_reader :owner
def initialize(owner: nil)
@owner = owner
end
end
# we can safely try to access the address even without risk of getting a nil error
# this first example throws an error
account = Account.new
p account.owner.address
# # error
# this is how we used to have to write ruby code to avoid the nil error
p account && account.owner && account.owner.address
# # => nil
# this is a more elequent way of writing the above
p account&.owner&.address
# => nil
# keyword arguments have a couple of advantages
# firstly you can use an identifer for an argument that you pass, or in other words you give it a name
# secondly you can pass the arguments in any order you like
# thirdly you can assign default values in your method parameters to avoid argument errors
def my_method(num_2: 0, num_1: 0)
num_1 + num_2
end
p my_method(num_2: 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment