How can I assign multiple values to a hash key?

后端 未结 4 625
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 13:55

For the sake of convenience I am trying to assign multiple values to a hash key in Ruby. Here\'s the code so far

myhash = { :name => [\"Tom\" , \"Dick\" ,         


        
4条回答
  •  余生分开走
    2020-12-30 15:00

    re: the issue of iterating over selective keys. Try using reject with the condition inverted instead of using select.

    e.g. given:

    {:name=>["Tom", "Dick", "Harry"], :keep=>[4, 5, 6], :discard=>[1, 2, 3]}
    

    where we want :name and :keep but not :discard

    with select:

    myhash.select { |k, v| [:name, :keep].include?(k) }
    => [[:name, ["Tom", "Dick", "Harry"]], [:keep, [4, 5, 6]]]
    

    The result is a list of pairs.

    but with reject:

    myhash.reject { |k, v| ![:name, :keep].include?(k) }
    => {:name=>["Tom", "Dick", "Harry"], :keep=>[4, 5, 6]}
    

    The result is a Hash with only the entries you want.

    This can then be combined with pierr's answer:

    hash_to_use = myhash.reject { |k, v| ![:name, :keep].include?(k) }
    hash_to_use.each_pair {|k,v| v.each {|n| puts "#{k} => #{n}"}}
    

提交回复
热议问题