gpt4 book ai didi

ruby - 如何将键值对 append 到 Ruby 中的现有哈希?

转载 作者:数据小太阳 更新时间:2023-10-29 07:22:00 26 4
gpt4 key购买 nike

<分区>

我是 Ruby 的新手,正在尝试将键/值对“注入(inject)”到 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

很抱歉将我的整个方法粘贴在这里。谁能帮我解决这个问题?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com