Ruts
Ruts

Reputation: 296

How to use if (without else) statement for multiple lines of code?

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

Upvotes: 0

Views: 2130

Answers (2)

Jean Bob
Jean Bob

Reputation: 565

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

Upvotes: 5

Anastasiia Tulentseva
Anastasiia Tulentseva

Reputation: 33

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.

Upvotes: 1

Related Questions