0

This question taught me how I can use an if statement without an else. I need the exact same thing, but for mutiple lines of code instead of one line of code.

I have tried this, but this does not seem to work:

def self.foo(a)
    {
    #mutiple lines of code
    }if a == true
end

2 Answers 2

5

This is very basic ruby syntax. All the ruby control structures can be used in inline way, or in multi-line/block way, closed with end keyword.

def self.foo(a)
  if a == true
    # mutiple lines of code
  end
end

For more informations about syntax and ruby best practices, you can refer to : this ruby style guide

Sign up to request clarification or add additional context in comments.

4 Comments

Your initial example was much cleaner.
You are right, I reverted my edit, and added an extra link for more syntax options/best practices informations.
BTW, "inline/block way" sounds contradictory, is that supposed to be "multi-line/block way"?
Little silly that I didn't try this. I assumed for some reason that this if statement had to be used with an else.
1

If you really want to do this, use parenteses, not curly braces:

def self.foo(a)
  (
    puts 'a'
    puts 'b'
  ) if a == true
end

Although I must warn you, this style is not at all common in ruby community. Use regular if syntax instead.

1 Comment

Oh, so it is possible this way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.