mardi 21 avril 2015

if / elsif to case statement in Ruby

I have a class which has private methods within it. I use a public method to call each of the private methods and check if a bingo card has bingo or not. Currently, it is written as such:

def check_card if check_horizontal == true bingo = "BINGO!" elsif check_vertical == true bingo = "BINGO!" elsif check_diagonal_right_to_left == true bingo = "BINGO!" elsif check_diagonal_left_to_right == true bingo = "BINGO!" else bingo = "Sorry, no Bingo." end puts "The result of your card is: #{bingo}" end

This currently works and passes my tests, however, I would like to be able to write the if/elsif statement as a case statement and have tried this:

def check_card bingo = case @bingo_card when check_horizontal then "BINGO!" when check_vertical then "BINGO!" when check_diagonal_right_to_left then "BINGO!" when check_diagonal_left_to_right then "BINGO!" else "Sorry, no bingo!" end puts "The result of your card is: #{bingo}" end

but it returns all of the tests as "Sorry, no bingo!"

Am I missing something with regard to case statement syntax? Below is the entire class:

class BingoScorer attr_reader :bingo_card def initialize(bingo_card=nil) @bingo_card = bingo_card end def add_card(card) @bingo_card = card end def check_card if check_horizontal == true bingo = "BINGO!" elsif check_vertical == true bingo = "BINGO!" elsif check_diagonal_right_to_left == true bingo = "BINGO!" elsif check_diagonal_left_to_right == true bingo = "BINGO!" else bingo = "Sorry, no Bingo." end puts "The result of your card is: #{bingo}" end private def check_horizontal i = 0 x_index_array = [] @bingo_card.length.times do if @bingo_card[i].join == "xxxxx" x_index_array << @bingo_card[i] end i += 1 end x_index_array.uniq.length == 1 ? true : false end def check_vertical i = 0 x_index_array = [] @bingo_card.length.times do x_index_array << @bingo_card[i].index('x') i += 1 end x_index_array.uniq.length == 1 ? true : false end def check_diagonal_right_to_left i = 0 x_index_array = [] @bingo_card.length.times do x_index_array << @bingo_card[i][i] i += 1 end x_index_array.uniq.length == 1 ? true : false end def check_diagonal_left_to_right idx1 = 0 idx2 = 4 x_index_array = [] @bingo_card.length.times do x_index_array << @bingo_card[idx1][idx2] idx1 += 1 idx2 -= 1 end x_index_array.uniq.length == 1 ? true : false end end

Thanks!

Aucun commentaire:

Enregistrer un commentaire