Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: 'case true' when does it block loop?

Tags:

ruby

There is piece of code

 A = "am"
    F = "fm"
    def fmam(n)
        return if n == 0
        loopy(n - 1)
        case true
        when n % 15 == 0
            puts B + L
        when n % 5 == 0
            puts L
        when n % 3 == 0
            puts B
        else
            puts n
        end
    end
    fmam(20)

in this code what does case true do it this code?

like image 633
Filip Bartuzi Avatar asked Aug 31 '26 14:08

Filip Bartuzi


2 Answers

case has two forms. The form you're using compares the "target" after the case keyword ( true in this case) with each comparison (the part after each when keyword) using the === operator. You end up with a series of boolean expressions and execute the code for the first one that evaluates to true. As such, it's redundant and a bit confusing. It would be better to remove the true and use the second form of case:

    case
    when n % 15 == 0
        puts B + L
    when n % 5 == 0
        puts L
    when n % 3 == 0
        puts B
    else
        puts n
    end

This does the same thing but is clearer.

like image 61
Darshan Rivka Whittle Avatar answered Sep 03 '26 03:09

Darshan Rivka Whittle


tutorialspoint :- says

case expression
[when expression [, expression ...] [then]
   code ]...
[else
   code ]
end

Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches.

saying that look below:

A = "am"
F = "fm"
L = "dd"
B = 'aa'
def fmam(n)
    return if n == 0

    case true
    when n % 15 == 0
        puts B + L
    when n % 5 == 0 # this evaluates to true first, which then matched with true value mentioned in the case statement.
        puts L
    when n % 3 == 0
        puts B
    else
        puts n
    end
end
fmam(20) #=> dd

Now look at the below code:

A = "am"
F = "fm"
L = "dd"
B = 'aa'
def fmam(n)
    return if n == 0

    case false
    when n % 25 == 0 # this evaluates to false first, which then matched with false value mentioned in the case statement.
        puts B + L
    when n % 5 == 0
        puts L
    when n % 3 == 0
        puts B
    else
        puts n
    end
end
fmam(30) #=> aadd
like image 22
Arup Rakshit Avatar answered Sep 03 '26 03:09

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!