Awais
Awais

Reputation: 1811

If modifier of Ruby is different than other languages

Its very simple question but I am at beginning level and little bit confused from if modifier of Ruby, i search on Google but not clear yet how it is different than other programming languages like java etc.

can anyone make me understand with simple example or refer to useful blog please.

Thanks in advance. :)

Upvotes: 2

Views: 5113

Answers (2)

Daniel Viglione
Daniel Viglione

Reputation: 9407

There is a gotcha with using the if modifier, which could be a source of bugs. The if modifier has very low precedence and binds more loosely than the assignment operator. That is, the assignment expression will supersede the modifier expression.

If x does not have a method named foo, then nothing happens at all, and the value of y is not modified.

y = x.foo if x.respond_to? :foo

In the second line, the if modifier applies only to the method call. If x does not have a foo method, then the modified expression evaluates to nil, and this is the value that is assigned to y.

y = (x.foo if x.respond_to? :foo)

This really could trip up your program. Again, y is not modified in first example. y is assigned value nil in second example:

y = x.foo if x.respond_to? :foo
y = (x.foo if x.respond_to? :foo)

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118261

Favor modifier if/unless usage when you have a single-line body. Like :

number = 4
puts "number is even" if number.even?
# >> "number is even"

If you have more than one line of logic, then use the traditional way to write it :

number = 4
if number.even?
  # some work with number then print it
  puts "number is even" 
end
# >> "number is even"

expr if expr

executes left hand side expression, if right hand side expression is true.

Upvotes: 6

Related Questions