Search code examples
rubyargumentscaseprocedure

Case code in Ruby program not working with a passed value


Have written some test code for a program, trying to pass 2 values, a file and a number. The below doesn't work at all, but if I have something like puts "test" (outside the case) it works.

def read_album(music_file, number)
    puts number #(this does something)
    case number.to_i
    when(number > 1)
            puts "done"
    when(number < 2)
            puts "something"
    when(number == 3)
        puts "none of this inside case is working"
    end
end

def main()
    a_file = File.new("albums.txt", "r")
    print("Choose album id: ")
    choice_of_album = gets().to_i
    read_album(a_file, choice_of_album)
end

main()

Solution

  • You need to drop the number.to_i from the case statement.

    Or do something like

    case number.to_i
        when 1..2 
            puts "foo"
        when 3..100
            puts "bar"
        else 
            puts "foobar"
        end
    end
    

    From the Ruby docs

    Case statements consist of an optional condition, which is in the position of an argument to case, and zero or more when clauses. The first when clause to match the condition (or to evaluate to Boolean truth, if the condition is null) “wins”, and its code stanza is executed. The value of the case statement is the value of the successful when clause, or nil if there is no such clause.

    Your version would evaluate to somehting like

    if (number > 1) === number.to_i
    

    and since you are comparing a number with a boolean expression this will not evaluate to true. If you had an else in the case statement this would have been called.