Peter's Blog

Redefining the Impossible

Ruby Notes 3


Endless Ends

Ruby terminates just about everything with the end keyword:

def SillyExample
  if a == 3
    10.repeat do |n|
      if n == a
        print n
      end
    end
  end
end

Maybe I am nesting too deep but the endless ends become quite confusing after a while, especially with ruby's official two space indents. Visual Basic 6 (ugh) at least has end if, loop, end sub etc so you know what you are looking at the end of.

Then again, python has no equivalent to end:

def SillyExample():
    if a == 3:
        for i in range(10):
            if n == a:
                print n

but python's indentation standard is four spaces rather than two making it a bit easier to follow.

Maybe I should just defy convention and indent my ruby with four spaces? Who cares apart from the indentation Nazis?

More Scope for Errors

So why wasn't this loop doing what I thought it would?

Mytable.find( :all, :order => "serial_number") do |oRecord|
    print oRecord.serial_number
end

Mytable is a rails ActiveRecord class and I'm using it to load records from a table. But nothing is printed although I am sure there are records there.

Hum, turns out I missed the call to the 'each' method:

Mytable.find( :all, :order => "serial_number").each do |oRecord|
    print oRecord.serial_number
end

and now it iterates through the recordset correctly. It seems that the first form silently does nothing, it doesn't seem to execute anything inside the block. It gives no errors either.


Filed under: noob ruby

MickTaiwan Says:

about 1 year ago

What about that ?

def SillyExample

10.repeat { |n| print n if n == a } if a == 3

end

Comments are Closed