Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 245
Tom Avatar asked Dec 07 '12 16:12

Tom


People also ask

How do you create a static method in Ruby?

Static Members in Ruby are declared with the help of the class. Since Ruby doesn't provide a reserved keyword such as static, when we make use of the class variable, then we create a static variable and then we can declare a method of that class in which the static variable is defined as a static method as well.

Can you have a public static method?

Static methods and variables include the keyword static before their name in the header or declaration. They can be public or private. Static variables belong to the class, with all objects of a class sharing a single static variable. Static methods are associated with the class, not objects of the class.

How do you create a static method?

Note: To create a static member(block, variable, method, nested class), precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

What is a public static method?

A static method in Java is a method that is part of a class rather than an instance of that class. Every instance of a class has access to the method. Static methods have access to class variables (static variables) without using the class's object (instance).


1 Answers

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

like image 156
devanand Avatar answered Sep 18 '22 17:09

devanand