100 Doors with Ruby

  • 本文关键字:Ruby with Doors ruby
  • 更新时间 :
  • 英文 :


我正在处理"罗塞塔密码100门"问题,遇到了麻烦。我发现"使用Ruby的100门帮助"有一些帮助,但我仍然无法让我的代码工作。

我的toggle方法在我的数组迭代方法中不起作用。

def toggle(state)
  if state == 'closed' 
    state.replace('open')
  elsif state == 'open'
    state.replace('closed')
  end
end
def one_hundred_doors(array)
  i = 0
  100.times do
    i += 1
    array.each_with_index.map do |state, index|
      if (index + 1) % i == 0
        toggle(state)
      end
    end
  end
  array.each_with_index { |state, door| puts "Door #{door + 1} is #{state}." }
end
doors = Array.new(100, "closed")
one_hundred_doors(doors)

有人能解释一下我做错了什么吗?

您的问题在于您的数组创建方法。您创建它以包含对同一字符串的100个引用:

doors = Array.new(100, "closed")
doors.first.replace("lala")
doors # => ["lala", "lala", ...]

但你需要不同的字符串。

这样创建:

doors = 100.times.map{"closed"}

最新更新