开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜