我是Ruby的新手,我正在努力注入' 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
很抱歉在这里粘贴我的整个方法。有人可以帮我这个吗?
答案 0 :(得分:11)
有三种方式:
.merge(other_hash)
返回包含other_hash内容和hsh内容的新哈希。
hash = { a: 1 }
puts hash.merge({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}
.merge!(other_hash)
将other_hash的内容添加到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)
答案 1 :(得分:1)
你可以merge!
两个哈希:
hash1 = {}
hash1.merge!({"a" => 1, "b" => 2})