我是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] => …Run Code Online (Sandbox Code Playgroud) 我试图each_with_index在数组上实现该方法.
def display_weapons
puts "Your current list of weapons are: "
@weapons.each_with_index do |weapon, index|
puts "#{index + 1}. #{weapon}"
end
end
Run Code Online (Sandbox Code Playgroud)
我称之为:
@weapons = ["Rockets", "Laser", "Photon blaster", "Plasma cannon"]
puts display_weapons
Run Code Online (Sandbox Code Playgroud)
我得到了结果:
Your current list of weapons are:
1. Rockets
2. Laser
3. Photon blaster
4. Plasma cannon
Rockets
Laser
Photon blaster
Plasma cannon
Run Code Online (Sandbox Code Playgroud)
我没有得到我想的那样.我只是想问一下这种方法是如何工作的.为什么我要两次获得元素?一旦指数+ 1,一次没有.