我是Ruby的新手,并尝试创建一个像游戏一样的小型Zork。我遇到以下几行代码时出现问题:
puts "Do an action"
action = gets.chomp
if action.include? 'look' && 'bed'
puts "you look at the bed"
elsif action.include? 'pickup' && 'bed'
puts "you pickup the bed"
else
puts "you do nothing"
end
出于某种原因,当我第一次在新文件中输入它时,它将起作用。如果我以任何方式更改代码,它只会给我第一次放置。
答案 0 :(得分:0)
你可以让补丁String
做类似的事情
class String
def include_all?(*args)
args.map{|arg| self.include?(arg)}.reduce(:&)
end
end
然后像
一样打电话action = "look a dog bed for sale"
action.include_all?("look","bed")
#=> true
action.include_all?("look","bed","fish")
#=> false
这样做需要提供尽可能多的参数,并使用splat Array
将它们放入*
,然后检查每个参数是否包含在String
中。然后使用&
运算符将它们减少为单个值,以便转换为
action = "look a dog bed for sale"
action.include_all?("look","bed")
#args = ["look","bed"]
#args.map{|arg| action.include?(arg)}
#=> [true,true]
#true & true
#=> true
action.include_all?("look","bed", "fish")
#args = ["look","bed","fish"]
#args.map{|arg| action.include?(arg)}
#=> [true,true,false]
#true & true & false
#=> false
其他建议是更标准的程序。我只想指出新的rubyists改变一个类是一个相当简单的过程。自行承担使用风险