-1

I have the following code:

def test_compare()
  if true
    condition = true
  else
    condition = false
  end

  assert_equal(true, condition)
end

In Ruby, variables inside of an if block have the same scope as variables declared outside of the if block according to "I don't understand ruby local scope".

Is it common practice to initialize variables inside of a control structure without first declaring them or initializing them outside of a control structure?

Coming from a Java.NET background this seems to make the code less readable and more prone to logic mistakes.

I am doing my best to "not write .NET code in Ruby", but want to understand why the above makes more sense than declaring scope variables at the beginning of the scope, or outside of the control structure.

Community
  • 1
  • 1
jeuton
  • 543
  • 3
  • 7

1 Answers1

3

if returns value. It's cleaner to use this behaviour.

x = if condition
  # several lines of calculations can be here
  'true value'
else
  # several lines of calculations can be here
  'false value'
end

Or, in this concrete case it's better to use ternary operator. It does the same thing and is shorter.

x = condition ? 'true value' : 'false value'
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367