我想生成一个数组,然后遍历它多次,并根据它们的状态对数组中的项目进行更改。我无法使条件语句正常工作
lockers = Array.new(900, "Closed");
#walk through and change every other item to "closed" if it is "open", and
"open" if it is "closed
(1...lockers.size).step(2).each { |i|
if lockers[i] = "Open"
lockers[i] = "Closed";
elsif (lockers[i] = "Closed")
lockers[i] = "Open";
end
lockers.join };
#walk through and change every 3rd item to "closed" if it is "open", and
"open" if it is "closed
(0...lockers.size).step(3).each { |i|
if (lockers[i] = "Open")
lockers[i] = "Closed";
elsif (lockers[i] = "Closed")
lockers[i] = "Open";
end
lockers.join; };
#walk through and change every 4th item to "closed" if it is "open", and "open" if it is "closed
(0...lockers.size).step(4).each { |i|
if (lockers[i] = "Open")
lockers[i] = "Closed";
elsif (lockers[i] = "Closed")
lockers[i] = "Open";
end
lockers.join; };
执行上述操作将正确地制作数组,并将所有内容都设置为“ Closed”。第一次遍历后,它无法将任何项目更改为“打开”。
如果我将条件更改为“ lockers [i] =“打开””,则显然可行。但是后来的条件语句也无法提取应有的每个项目。
答案 0 :(得分:1)
这是您可以做到的一种方法。
def flip(lockers, n)
h = { "closed"=>"open", "open"=>"closed" }
(0..lockers.size-1).step(n).each { |i| lockers[i] = h[lockers[i]] }
lockers
end
lockers = 6.times.map { ["open", "closed"].sample }
#=> ["open", "closed", "open", "closed", "closed", "open"]
flip(lockers, 2)
#=> ["closed", "closed", "closed", "closed", "open", "open"]
lockers
#=> ["closed", "closed", "closed", "closed", "open", "open"]
lockers = ["open", "closed", "open", "closed", "closed", "open"]
flip(lockers, 3)
#=> ["closed", "closed", "open", "open", "closed", "open"]
lockers = ["open", "closed", "open", "closed", "closed", "open"]
flip(lockers, 4)
#=> ["closed", "closed", "open", "closed", "open", "open"]
以下是另一种方式。
def flip(lockers, n)
h = { "closed"=>"open", "open"=>"closed" }
lockers.map!.with_index { |s,i| (i % n).zero? ? h[s] : s }
end
我假设通过“其他所有项目”,要翻转的第一个元素是数组的第一个元素。 (请注意,数组的最后一个元素的索引为lockers.size-1
,而不是lockers.size
。)
我了解您希望修改现有阵列,所以这就是我所做的。要返回一个新数组并保持原始数组不变(通常是首选做法),只需将map!
替换为map
。
请参见Array#map!和 Array#map。