Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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 brackets to do this? I read about blocks also but not sure how can they be used in if/else expressions.

like image 845
Jeet Avatar asked Sep 14 '10 17:09

Jeet


People also ask

Does Ruby use curly braces?

Ruby blocks are anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or curly braces {}.

What are {} in Ruby?

The curly brackets { } are used to initialize hashes. The documentation for initializer case of { } is in ri Hash::[] The square brackets are also commonly used as a method in many core ruby classes, like Array, Hash, String, and others.

When should curly brackets be used?

Curly brackets are rarely used in prose and have no widely accepted use in formal writing, but may be used to mark words or sentences that should be taken as a group, to avoid confusion when other types of brackets are already in use, or for a special purpose specific to the publication (such as in a dictionary).

What is {} used for in code?

Brackets, or braces, are a syntactic construct in many programming languages. They take the forms of "[]", "()", "{}" or "<>." They are typically used to denote programming language constructs such as blocks, function calls or array subscripts. Brackets are also known as braces.


2 Answers

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.

like image 76
Chuck Avatar answered Oct 03 '22 08:10

Chuck


This is cute:

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

Use as follows:

my_if(token == "hello") { 
    puts "hello encountered!" 
}
like image 39
horseyguy Avatar answered Oct 03 '22 07:10

horseyguy