如何将键值对附加到 Ruby 中的现有散列?
How do I append a key value pair to an existing hash in Ruby?
我是 Ruby 的新手,正在尝试 'inject' key/value 与 Ruby 中的现有哈希配对。我知道您可以使用 << 对数组执行此操作,例如
arr1 = []
a << "hello"
但是我可以为散列做类似的事情吗?所以像
hash1 = {}
hash1 << {"a" => 1, "b" => 2}
基本上,我正在尝试根据条件在循环中推送键值对。
# Encoder: This shifts each letter forward by 4 letters and stores it in a hash called cipher. On reaching the end, it loops back to the first letter
def encoder (shift_by)
alphabet = []
cipher = {}
alphabet = ("a".."z").to_a
alphabet.each_index do |x|
if (x+shift_by) <= 25
cipher = {alphabet[x] => alphabet[x+shift_by]}
else
cipher = {alphabet[x] => alphabet[x-(26-shift_by)]} #Need this piece to push additional key value pairs to the already existing cipher hash.
end
end
很抱歉将我的整个方法粘贴到这里。谁能帮我解决这个问题?
您可以 merge!
将两个哈希放在一起:
hash1 = {}
hash1.merge!({"a" => 1, "b" => 2})
有3种方式:
.merge(other_hash)
Returns a new hash containing the contents of other_hash and the contents of hsh.
hash = { a: 1 }
puts hash.merge({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}
.merge!(other_hash)
Adds the contents of other_hash to hsh.
hash = { a: 1 }
puts hash.merge!({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}
最有效的方法是修改现有哈希值,直接设置新值:
hash = { a: 1 }
hash[:b] = 2
hash[:c] = 3
puts hash # => {:a=>1, :b=>2, :c=>3}
这些方法的相应基准:
user system total real
0.010000 0.000000 0.010000 ( 0.013348)
0.010000 0.000000 0.010000 ( 0.003285)
0.000000 0.000000 0.000000 ( 0.000918)
我是 Ruby 的新手,正在尝试 'inject' key/value 与 Ruby 中的现有哈希配对。我知道您可以使用 << 对数组执行此操作,例如
arr1 = []
a << "hello"
但是我可以为散列做类似的事情吗?所以像
hash1 = {}
hash1 << {"a" => 1, "b" => 2}
基本上,我正在尝试根据条件在循环中推送键值对。
# Encoder: This shifts each letter forward by 4 letters and stores it in a hash called cipher. On reaching the end, it loops back to the first letter
def encoder (shift_by)
alphabet = []
cipher = {}
alphabet = ("a".."z").to_a
alphabet.each_index do |x|
if (x+shift_by) <= 25
cipher = {alphabet[x] => alphabet[x+shift_by]}
else
cipher = {alphabet[x] => alphabet[x-(26-shift_by)]} #Need this piece to push additional key value pairs to the already existing cipher hash.
end
end
很抱歉将我的整个方法粘贴到这里。谁能帮我解决这个问题?
您可以 merge!
将两个哈希放在一起:
hash1 = {}
hash1.merge!({"a" => 1, "b" => 2})
有3种方式:
.merge(other_hash)
Returns a new hash containing the contents of other_hash and the contents of hsh.
hash = { a: 1 }
puts hash.merge({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}
.merge!(other_hash)
Adds the contents of other_hash to hsh.
hash = { a: 1 }
puts hash.merge!({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}
最有效的方法是修改现有哈希值,直接设置新值:
hash = { a: 1 }
hash[:b] = 2
hash[:c] = 3
puts hash # => {:a=>1, :b=>2, :c=>3}
这些方法的相应基准:
user system total real
0.010000 0.000000 0.010000 ( 0.013348)
0.010000 0.000000 0.010000 ( 0.003285)
0.000000 0.000000 0.000000 ( 0.000918)