如何将键值对附加到Ruby中的现有哈希?

Sea*_*ino 4 ruby hash append

我是Ruby的新手,我正在尝试将键/值对"注入"Ruby中的现有哈希.我知道你可以使用<< for arrays,例如

arr1 = []
a << "hello"
Run Code Online (Sandbox Code Playgroud)

但我可以为哈希做类似的事情吗?所以像

hash1 = {}
hash1 << {"a" => 1, "b" => 2}
Run Code Online (Sandbox Code Playgroud)

基本上,我正在尝试基于条件的循环中的键值对.

# 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
Run Code Online (Sandbox Code Playgroud)

很抱歉在这里粘贴我的整个方法.有人可以帮我这个吗?

Rus*_*nov 12

有3种方式:

.merge(other_hash) 返回包含other_hash的内容和hsh内容的新哈希.

hash = { a: 1 }
puts hash.merge({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}
Run Code Online (Sandbox Code Playgroud)

.merge!(other_hash) 将other_hash的内容添加到hsh.

hash = { a: 1 }
puts hash.merge!({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}
Run Code Online (Sandbox Code Playgroud)

最有效的方法是修改现有哈希,直接设置新值:

hash = { a: 1 }
hash[:b] = 2
hash[:c] = 3
puts hash # => {:a=>1, :b=>2, :c=>3}
Run Code Online (Sandbox Code Playgroud)

这些方法的相应基准:

       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)
Run Code Online (Sandbox Code Playgroud)