2015-06-21 61 views
0

如何獲取.include?上班?當用戶選擇一個字符時,我希望控制檯打印puts ok語句,然後轉到if語句。如何使用.include?在Ruby中使用散列語句

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 

回答

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

以上的答案是偉大的,真棒功能重構,但我會用

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將您的輸入轉換回整數。

+0

謝謝你讓這個更清晰 – Andeski

相關問題