tags:

views:

82

answers:

4

I've recently moved from C# to Ruby, and I find myself missing the ability to make collapsible, labelled regions of code. It just occurred to me that it ought to be OK to do this sort of thing:

class Example
  begin # a group of methods

    def method1
      ..
    end

    def method2
      ..
    end

  end

  def method3
    ..
  end
end

...but is it actually OK to do that? Do method1 and method2 end up being the same kind of thing as method3? Or is there some Ruby idiom for doing this that I haven't seen yet?

+1  A: 

Yes, it is okay to do that (i.e. it doesn't change the semantics of your code).

However this isn't a common pattern and it might be confusing to readers of your code who wouldn't understand what the purpose of the begin ... end block is.

sepp2k
+1  A: 

I think it should be OK. I haven't seen it a lot though. Another way you could accomplish the same thing, while using less indentation, is to close and reopen the class, like so:

class Example
  def method1
    ..
  end

  def method2
    ..
  end
end

# optionally put some other code here

class Example
  def method3
    ..
  end
end

I think this is often used so that you can put other code in the middle, such as when there's a constant defined in the first class Example block, which is used to define a constant in the middle code, which is used to define a constant in the second class Example block. That way you never have to refer to a constant before it's defined.

wdebeaum
+5  A: 

Adding arbitrary Ruby code in order to please your editor doesn't seem reasonable to me at all. I think you should try to get a decent text editor, one that would be able to configure to use some keyword you put in your comments to enable code folding there, for example:

# region start AAA

some(:code, :here)

# region end AAA

And if you allow me to be sarcastic: you should know that Ruby is lot more expressive, elegant and pretty than C#, and chances are that there isn't any Ruby code ought to be hidden in the first place! ;)

Mladen Jablanović
Formal comments like this are code too, IMHO. So by your logic they're also unreasonable ;)
wdebeaum
Formally, you're right. ;)
Mladen Jablanović
+2  A: 

As others have said this doesn't change the method definition.

However, if you want to label groups of methods, why not use Ruby semantics to label them? You could use modules to split your code into chunks that belong together. This is good practice for large classes, even if you don't reuse the modules. When the code grows, it will be easy to split the modules into separate files for better organisation.

class Example
  module ExampleGroup
    def method1
      # ..
    end

    def method2
      # ..
    end
  end
  include ExampleGroup

  def method3
    # ..
  end
end
molf