Skip to content

Instantly share code, notes, and snippets.

@prodis
Last active Dec 11, 2015
Embed
What would you like to do?
Ruby Fundamental - Uma maneira não trivial de acessar valores de hash
my_hash[:status] if my_hash
# or
my_hash[:status] unless my_hash.nil?
class MyClass
attr_accessor :some_value
end
m = MyClass.new
m.some_value = 456 # => 456
m.some_value # => 456
m.try(:some_value) # => 456
m.try(:some_value=, 123) # => 123
m.some_value # => 123
m = nil
m.some_value = 123 # => NoMethodError: undefined method `some_value=' for nil:NilClass
m.some_value # => NoMethodError: undefined method `some_value' for nil:NilClass
m.try(:some_value=, 123) # => nil
m.try(:some_value) # => nil
my_hash = { one: 111, two: 222, three: 33 }
my_hash.try(:[:one])
# SyntaxError: unexpected '[', expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
# my_hash.try(:[:one])
# ^
my_hash = { one: 111, two: 222, three: 33 }
my_hash.try("[:one]".to_sym)
# NoMethodError: undefined method `[:one]' for {:one=>111, :two=>222, :three=>33}:Hash
my_hash = { one: 111, two: 222, three: 33 }
my_hash.try(:[], :one) # => 111
my_hash = { one: 111, two: 222, three: 33 }
my_hash[:one] # => 111
my_hash.[](:one) # => 111
my_hash.[] :one # => 111
my_hash.[]:one # => 111
my_hash = { one: 111, two: 222, three: 33 }
my_hash[:two] = 2
my_hash.[]=(:two, 2)
my_hash.[]= :two, 2
my_hash.[]=:two, 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment