tags:

views:

121

answers:

3

I'm learning Ruby but came across a very annoying thing: I can't 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 stuff

+4  A: 

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

Paul Schreiber
+9  A: 

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.

Chuck
but it gets messy for big constructs..
iAdam
+1 for stressing the importance of proper indention over braces. Raedability is king.
Banang
@iAdam: I'm sorry — what gets messy for big constructs?
Chuck
@iAdam: You mean if you have many indentation levels? That's why you should refactor your code into small and readable portions ie. methods.
Lars Haugseth
if you have a big construct, your construct is doing too much. Maybe take a quick look at common code smells: http://en.wikipedia.org/wiki/Code_smell
Jed Schneider
Yes, indentation gets messy for big "constructs." But that just means your code isn't very good. Huge, long methods with multiple levels of loops and conditionals isn't Ruby's style. Instead, break down each part into smaller methods that serve single purposes and are easy to understand. Compose larger tasks from these methods, and this confusing indentation problem will disappear.
AboutRuby
+2  A: 

This is cute:

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

Use as follows:

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