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.
Ruby blocks are anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or curly braces {}.
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.
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).
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.
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!"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With