开发者

Can I use curly brackets in Ruby's if/else?

开发者 https://www.devze.com 2023-01-16 07:30 出处:网络
Why can\'t I use curly brackets in if/else constructs? I left Python as I didn\'t feel comfortable with indenting the statements carefully.

Why can't I use curly brackets in if/else constructs? I left Python as I didn't feel comfortable with indenting the statements carefully.

Is this the same way in Ruby also?

For example, can I write something like this?

if token == "hello" {
  puts "hello encountered"
  # lots of lines here
}

Is there any way of using curly brack开发者_运维问答ets to do this? I read about blocks also but not sure how can they be used in if/else expressions.


You can't use curly braces, but indentation doesn't matter either. Instead of a closing brace, Ruby uses the end keyword.

if token == "hello"
  puts "hello encountered"
  # lots of lines here
end

I'd still recommend indenting carefully, though — poorly indented code will trick human readers even if braces are used correctly.


This is cute:

def my_if(condition, &block)
    block.call if condition
end

Use as follows:

my_if(token == "hello") { 
    puts "hello encountered!" 
}


Nope. You need to use end instead of a }.

0

精彩评论

暂无评论...
验证码 换一张
取 消