Can I improve this method with duck print?

I hope I did not understand the meaning of duck printing, but from what I read, it means that I have to write code based on how the object responds to methods and not to type / class.

Here is the code:

def convert_hash(hash)
  if hash.keys.all? { |k| k.is_a?(Integer) }
    return hash
  elsif hash.keys.all? { |k| k.is_a?(Property) }
    new_hash = {}
    hash.each_pair {|k,v| new_hash[k.id] = v}
    return new_hash
  else
    raise "Custom attribute keys should be ID or Property objects"
  end
end

I want to end up with a hash where the keys are an integer representing the identifier of an ActiveRecord object. I don’t particularly like going through hash keys twice with all?to determine if I need to capture the identifier.

Of course, I will accept any other suggestions for improving this code :)

+5
source share
3 answers

, , , . , , . - :

def convert(hash)
    new_hash = {}
    hash.each_pair { |k,v| new_hash[ k.is_a?(Integer) ? k : k.id ] = v }
    return new_hash
end

, , id. , , , id, , , , . , .

, , .

+11

- . , Java, , , . , Ruby, , .

, . , , , , (.. [Foo]). Property . , elseif.

, , , , , . , , , , , .

+3

, , , ActiveRecord.

, , / . - :

h = {}
def h.put obj
  self[obj.id]=obj
end

, ,

h = {}
def h.[]= key, value
  raise "hell" unless key == value.id
  super
end
0
source

All Articles