g0rd
g0rd

Reputation: 143

Why are there two if's on single line conditional?

I am very very new to ruby. Could anyone decode this for me?

page = 1 if page <= 0 if @type != 'something'

My guess is something like:

if (page <= 0 && @type != 'something')
then page = 1 

Upvotes: 2

Views: 42

Answers (2)

ddavison
ddavison

Reputation: 29082

another way to understand it, is just to break it down statement by statement

doThis if doThat

Is the same as writing

if doThat
  doThis
end

so...

page = 1 if page <= 0 if @type != 'something'

is

if @type != 'something'
  if page <= 0
    page = 1
  end
end

Upvotes: 4

sawa
sawa

Reputation: 168249

Your rewritting:

if (page <= 0 && @type != 'something')

is close, but is not correct. Your original line would be interpreted as:

(page = 1 if page <= 0) if @type != 'something'

which means that @type != 'something' is first evaluated, and the rest is shortcut if the condition is falsy at that point. This means your original line can be rewritten as:

if (@type != 'something' && page <= 0)

Upvotes: 4

Related Questions