如果语句也使用.include?和&&在红宝石

时间:2014-10-10 14:37:25

标签: ruby if-statement operators

我是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

出于某种原因,当我第一次在新文件中输入它时,它将起作用。如果我以任何方式更改代码,它只会给我第一次放置。

1 个答案:

答案 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改变一个类是一个相当简单的过程。自行承担使用风险