怎么用.include?在Ruby中使用哈希语句

时间:2015-06-21 19:17:20

标签: ruby command-line-interface

如何获得.include?上班?当用户选择一个字符时,我希望控制台打印puts ok语句,然后转到if语句。

  name = {"1" => "Mario",
            "2" => "Luigi",
            "3" => "Kirby",
            }
        puts "Peach's apocalypse, will you survive?"

    def character (prompt, options)
        puts = "who will you be?"
        options = name[1] || name[2] || name[3]
        character = gets.chomp.downcase
    until character.include? name
    end


    puts "ok #{name} all three of you run out of peach's castle which has been overrun"

    if character = name[1] || name[2] || name[3]
        puts ("zombies are in the castle grounds, there are weapons over the bridge")
        puts "What do you do, charge through or sneak?"
        x = gets.chomp.downcase
                if x == "sneak"
                    puts "oh you died"
                if x == "charge through"
                    puts "the zombies tumbled over the bridge's edge, you made it safe and sound"
                else
                    puts "you did nothing and were eaten alive by Princess Peach"
    end
    end
    end
    end

2 个答案:

答案 0 :(得分:1)

看起来你在字符串上调用include?。如果您将其自身的子字符串传递给它,则只会返回true。例如:

"Mario".include?("Mar") #=> true

您想在include?哈希中的键数组上调用name。你可以这样做:

name.values.include?(character)

或更简洁

name.has_value?(character)

以下是关于the include? method of the Array classthe include? method of the string class以及the has_value? method of the Hash class的一些文档。

还有更多需要修改的程序才能运行,就像你期望的那样。这是一个有效的实施方案:

puts "Peach's apocalypse, will you survive?"

names = {
  "1" => "Mario",
  "2" => "Luigi",
  "3" => "Kirby"
}

def choose_character(character = "", options)
  puts = "who will you be?"
  options.each do |num, name|
    puts "#{num}: #{name}"
  end

  until options.has_key? character or options.has_value? character
    character = gets.chomp.capitalize
  end

  return options[character] || character
end

name = choose_character(names)

puts "ok #{name} all three of you run out of peach's castle which has been overrun"
puts "zombies are in the castle grounds, there are weapons over the bridge"
puts "What do you do, charge through or sneak?"

case gets.chomp.downcase
when "sneak"
  puts "oh you died"
when "charge through"
  puts "the zombies tumbled over the bridge's edge, you made it safe and sound"
else
  puts "you did nothing and were eaten alive by Princess Peach"
end

答案 1 :(得分:1)

上面的答案很棒,并且具有很棒的重构功能,但我会使用

character = gets.strip.downcase

相反,它也消除了任何潜在的空白。

要详细说明字符串的内容,'gets'代表'get string'(或者至少是我教过的),所以你通过'gets'获得的所有内容都将是一个字符串,直到你进一步转换它为止。考虑一下:

2.2.1 :001 > puts "put in your input"
put in your input
=> nil 
2.2.1 :002 > input = gets.strip
5
=> "5" 
2.2.1 :003 > input.class
=> String 

您必须使用.to_i将输入转换回整数。