Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it matter if a conditional statement comes before or after the expression?

Sorry if this is a stupid question but I'm a C# guy fumbling his way around ruby..

in ruby i notice a lot of people do this:

do_something(with params) if 1 = 1

is there any difference (even slight) between that and this:

if 1 = 1 do_something(with params)

or is it the same thing written for better clarity?

like image 818
Daniel Upton Avatar asked Dec 21 '10 14:12

Daniel Upton


People also ask

What happens in the main clause of a conditional sentence?

The main clause is the result of that condition. What happens in the main clause is conditional to what happens in the if-clause. In other words, the main clause only happens when the events in the if-clause happen. Note: There are two ways of ordering a conditional sentence.

What is conditional statement?

Conditional Statement Definition A conditional statement is represented in the form of “if…then”. Let p and q are the two statements, then statements p and q can be written as per different conditions, such as;

What is a complete conditional sentence?

Complete conditional sentences contain a conditional clause (often referred to as the if-clause) and the consequence. Consider the following sentences: If a certain condition is true, then a particular result happens.

Why do we use first conditional sentences?

This is because the outcome will always be the same, so it doesn’t matter “if” or “when” it happens. First conditional sentences are used to express situations in which the outcome is likely (but not guaranteed) to happen in the future. Look at the examples below:


1 Answers

The latter is syntactically invalid. You would need to write:

if 1==1 then do_something(with params) end

Single-line conditionals must always trail. And yes, there is a difference. Try these out:

bar1 = if foo1=14
  foo1*3
end
#=> 42

bar2 = foo2*3 if foo2=14
#=> NameError: undefined local variable or method `foo2' for main:Object

In the latter, Ruby sees the assignment after the reference and so treats foo2 as a method instead of a local variable. This is only an issue when:

  • You are intentionally using assignment (not testing for equality) in a conditional, and
  • This is the first time (in terms of source order) that this variable has been assigned in the scope.
like image 84
Phrogz Avatar answered Sep 28 '22 06:09

Phrogz