Strange_ruby
Some things are weird with Ruby…
hash = {name: 'Olle', age: 12}
struct = Struct.new(:name, :age).new('Olle', 12)
p hash.name rescue 'NoMethodError'
p hash[:name] # => "Olle"
p struct.name # => "Olle"
p struct[:name] # => "Olle"
p hash[:color] # => nil
p struct.color rescue 'NoMethodError'
p hash.key?(:name) # => true
p hash.member?(:name) # => true
# So, in a Hash member? is alias for key?
# Struct do not have the method .key?
p struct.key?(:name) rescue 'NoMethodError'
# It has the method .member?
p struct.member?(:name) # => false
# And the struct method .member? check the values.. not the keys.
p struct.values # => ["Olle", 12]
p struct.member?('Olle') # => true
# If you want to see the members.. just use .members
# (but do not check if a member is present with .member?)
p struct.members # => [:name, :age]
# Is this how we are supposed to check if a member (key) is present?
p struct.members.include?(:name) # => true
p '-'*80
# A Struct must be checked like this
p begin
struct.surpuppa
rescue NoMethodError
# will return nil
end # => nil
# or like this
p struct.surpuppa if struct.members.include?(:surpuppa) # no output
p local_variables # => [:hash, :struct, :kossa]
if 13 == 100
kossa = 'mu'
end
# local variable kossa is created and set to nil just being mentioned
# inside a conditional (false) block.
p my_unassigned_variable rescue 'NameError'
p kossa # => nil
Made some changes to Struct class
str = Struct.new(:name, :age, :xtra).new('Olle', 13, nil)
class Struct
alias :value? :member?
def member?(key) = self.members.include?(key)
def on_member(key, &bl)
(yield(self[key]) if member?(key)) if bl
end
end
p str.member? :xtra # => true
p str.member? :ixtra # => false
p str.value? 'arne' # => true
p str.value? 37 # => false
str.on_member(:name) { p it }
str.on_member(:fis) { p 'will not print' }
str.on_member(:xtra) { p 'that is a nil value' }