Ruby:初始化哈希时减少重复

时间:2011-02-11 01:03:46

标签: ruby

array = [0, 0.3, 0.4, 0.2, 0.6]

hash = {
   "key1" => array[0..2],
   "key2" => array[0..3],
   "key3" => array,
   "key4" => array,
   "key5" => array,
   "key6" => array,   
   "key7" => array
}

有没有办法可以通过执行类似

的操作来删除重复项
hash = {
   "key1" => array[0..2],
   "key2" => array[0..3],
    %(key3, key4, key5, key6, key7).each {|ele| ele => array}
}

4 个答案:

答案 0 :(得分:4)

尝试

array = [0, 0.3, 0.4, 0.2, 0.6]
hash = {
   "key1" => array[0..2],
   "key2" => array[0..3]
}
%w(key3 key4 key5 key6 key7).each {|ele| hash[ele] = array}

答案 1 :(得分:3)

array = [0, 0.3, 0.4, 0.2, 0.6]
h = Hash[*Array.new(7) {|x| ["key#{x+1}", array[0..(x<2?x+2:-1)]]}.flatten(1)]
h # => {"key1" => [0, 0.3, 0.4], "key2" => [0.3, 0.4, 0.2],...}

答案 2 :(得分:0)

以下是主题的几个变体。它们适用于1.8.7或1.9.2。插入顺序保持1.9.2'因为它的作用:

require 'pp'

array = [0, 0.3, 0.4, 0.2, 0.6]

hash = ('key3'..'key7').entries.inject({}) { |m, e| m[e] = array; m }
hash.merge!('key1' => array[0..2], 'key2' => array[0..3])
pp hash 

puts '-' * 40

hash = {
  'key1' => array[0..2], 
  'key2' => array[0..3]
  }.merge(('key3'..'key7').entries.inject({}) { |m, e| m[e] = array; m })
pp hash

puts '-' * 40

# I think this is the most readable/maintainable
hash = {
  'key1' => array[0..2], 
  'key2' => array[0..3]
}
('key3'..'key7').entries.inject(hash) { |m, e| m[e] = array; m }
pp hash

哪个输出:

# >> {"key3"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key4"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key5"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key6"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key7"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key1"=>[0, 0.3, 0.4],
# >>  "key2"=>[0, 0.3, 0.4, 0.2]}
# >> ----------------------------------------
# >> {"key1"=>[0, 0.3, 0.4],
# >>  "key2"=>[0, 0.3, 0.4, 0.2],
# >>  "key3"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key4"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key5"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key6"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key7"=>[0, 0.3, 0.4, 0.2, 0.6]}
# >> ----------------------------------------
# >> {"key1"=>[0, 0.3, 0.4],
# >>  "key2"=>[0, 0.3, 0.4, 0.2],
# >>  "key3"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key4"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key5"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key6"=>[0, 0.3, 0.4, 0.2, 0.6],
# >>  "key7"=>[0, 0.3, 0.4, 0.2, 0.6]}

答案 3 :(得分:0)

这是另一个版本:

hash = {
   "key1" => array[0..2],
   "key2" => array[0..3]
}.tap { |h| ("key3".."key7").each{|k| h[k]=array}}