有没有更好的方法在if语句中编写多个OR语句?

时间:2014-08-15 03:27:30

标签: ruby if-statement

def get_string(no_of_times)
    1.upto(no_of_times) do 
    string_input = gets.chomp
    count_holes(string_input)
    end 
end

def count_holes(word)
    count = 0
    word.each_char do |char|
        if char == "A" || char == "D" || char == "O" || char == "P" || char == "Q" || char == "R" 
            count += 1
        elsif char == "B"
            count += 2
        end
    end
    $arr_of_holes << count
end



test_cases = gets.chomp.to_i

$arr_of_holes = []
get_string(test_cases)
puts $arr_of_holes

大家好。迭代每个字符时,我不喜欢if语句中的长条件。所以我想问你们所有人是否有更好的办法在ruby中做到这一点。

由于

4 个答案:

答案 0 :(得分:5)

这可以通过案例选择来完成,如multiple terms can be supplied to each when

case char
when "A", "D", "O", "P", "Q", "R"
  count += 1
when "B"
  count += 2
end

答案 1 :(得分:3)

您可以使用Array#include?

if %q{A D O P Q R}.include? char
    count += 1
elsif char == "B"
    count += 2
end
使用Hash

替代方式:

def count_holes(word)
    holes = {
        'A' => 1,
        'D' => 1,
        'O' => 1,
        'P' => 1,
        'Q' => 1,
        'B' => 2,
    }
    count = word.chars.map { |char| holes.fetch(char, 0) }.inject :+
    $arr_of_holes << count
end

答案 2 :(得分:1)

比nacyot的答案稍微紧凑:

count += case char
when "B" then 2
when "A", "D", "O".."R" then 1
else 0
end

如果没有这种情况,则可能不需要else行。

答案 3 :(得分:0)

还有一种方法:

   word = "BROADLY"
   "ADOPQR".each_char.reduce(0) { |t,c| t + word.count(c) } + 2*word.count("B")
     #=> 6