junky
junky

Reputation: 1478

ruby error - can I convert this block into a single line with {...}?

I created the following (this is part of more code but only this line is at issue):

if number_to_test % divisor == 0 then number_of_divisors+= 1 end

I wanted to shorten it up with

if number_to_test % divisor == 0 { number_of_divisors+= 1 }

but I get

syntax error, unexpected '{', expecting keyword_then or ';' or '\n'
    if number_to_test % divisor == 0 { number_of_divisors+= 1 }
                                      ^
 syntax error, unexpected '}', expecting keyword_end

I thought I could change the long form into a {}
Can you tell me the right syntax (if possible) ?
Maybe I'm just thinking of do end blocks rather than if statements?

Upvotes: 1

Views: 94

Answers (3)

xdazz
xdazz

Reputation: 160873

number_of_divisors+= 1 if number_to_test % divisor == 0

would be better.

Fixed: ruby doesn't have ++.

Upvotes: 0

Andrew Marshall
Andrew Marshall

Reputation: 96984

One line if statements in Ruby are done "backwards", so to speak:

number_of_divisors += 1 if number_to_test % divisor == 0

As might be expected, the same works with unless as well.

Upvotes: 5

Edu
Edu

Reputation: 1969

You could do:

number_of_divisors+= 1 if number_to_test % divisor == 0 

Upvotes: 1

Related Questions