-2

I have a Ruby method:

class ClassOfSomeSort
  def self.methodOfSomeSort(argument)
  ...
  end

  methodOfSomeSort(5)

end

I heard calling the method in the class itself is a bad practise.

Where should I call it? In C++ there's an int main function where it is done, but where is it done in Ruby?

the Tin Man
  • 150,910
  • 39
  • 198
  • 279
Jes
  • 283
  • 1
  • 14
  • You can just write your code (that would be in main) at the ["top level"](http://stackoverflow.com/questions/9687106/is-there-a-main-method-in-ruby-like-in-c) so to speak. Or you can look at [this SO question](http://stackoverflow.com/questions/582686/should-i-define-a-main-method-in-my-ruby-scripts) – UnholySheep Oct 03 '16 at 20:21
  • 1
    I failed to see why it is bad. – Aetherus Oct 03 '16 at 20:30
  • 2
    As a note, in Ruby method names should be like `method_of_some_sort`, avoiding capitals and using underscores instead. Classes are like what you have there. – tadman Oct 03 '16 at 21:57
  • You're getting down voted, most likely because people think you haven't put in enough effort. I'd suggest reading "[ask]" and "[How much research effort is expected of Stack Overflow users?](http://meta.stackoverflow.com/a/261593/128421)". I'd also suggest reading some tutorials. – the Tin Man Oct 04 '16 at 00:35

3 Answers3

0

Ruby is an interpreted language, so simple program may look like this:

print "Hello, World!"

And that's all. You can run this program from command line calling ruby fileName.rb. In your example you can just call it after the class declaration:

class ClassX
  def self.MethodOfMine(argument)
    # method
  end
end

ClassX.MethodOfMine(5)
rsqLVo
  • 358
  • 3
  • 8
  • `Class` is a core object class. Also creating an instance of this class and then calling methods on it means those are instance methods, which they're not. – tadman Oct 03 '16 at 21:57
0

You can call class methods at any time and in any context:

class Example
  def self.demo!
    puts "Hello, world!"
  end
end

Example.demo!

This is unlike instance methods where you need to create an instance of something. If you have no instance methods, nor any use for them, instead define a module much the same way.

tadman
  • 194,930
  • 21
  • 217
  • 240
0
class Example
 def self.methodOfMine(argument)
 ...
 end
end

object = Example.methodOfMine(InsertAnything)

Call the method outside the class by creating an instance :)