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?
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.
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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With