Is there a better way to write multiple OR statements in an 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

      

Hello to all. I don't like the lengthy condition in the if statement, repeating every character. So I wanted to ask you all if there is a better way to do this in ruby.

thank

+3


source to share


4 answers


You can use Array#include?

:

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

      



Alternative way 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

      

+3


source


This can be done on a case-by-case basis, as several terms can be provided for eachwhen

:



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

      

+5


source


Slightly more compact than nacyot's answer:

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

      

The line else

may not be required if this is not the case.

+1


source


Another way:

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

      

0


source







All Articles