Tom Tom - 6 months ago 28
Ruby Question

Ruby: How to make a public static method?

In Java i might do:

public static void doSomething();


And then i can access the method statically without making an instance:

className.doSomething();


How can i do that in Ruby? this is my class and from my understanding
self.
makes the method static:

class Ask

def self.make_permalink(phrase)
phrase.strip.downcase.gsub! /\ +/, '-'
end

end


But when i try to call:

Ask.make_permalink("make a slug out of this line")


I get:

undefined method `make_permalink' for Ask:Class


Why is that if i haven't declared the method to be private?

Answer

Your given example is working very well

class Ask
  def self.make_permalink(phrase)
    phrase.strip.downcase.gsub! /\ +/, '-'
  end
end

Ask.make_permalink("make a slug out of this line")

I tried in 1.8.7 and also in 1.9.3 Do you have a typo in you original script?

All the best

Comments