Is static
in Java like self
in Ruby?
self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.
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.
In Java programming, the main motivation for making a method static is convenience. You can call a static method without creating any object, just by using its class name. So if you need a method, which you want to call directly by class name, make that method static.
Whenever you return values from a static method they are either static nor instance by default, they are just values. The user invoking the method can use them as he wants. i.e. you can retrieve the values and declare them static.
No. Java's static
and Ruby's self
have absolutely nothing whatsoever to do with each other.
The Java equivalent to Ruby's self
is this
. The Ruby equivalent to Java's static
does not exist.
Java's static
means that the method is dispatched statically instead of dynamically. In Ruby, methods are always dispatched dynamically. static
means that the method is not called on any object. In Ruby, methods are always called on objects. Since static
methods in Java aren't associated with any object, they don't have access to any object state. In Ruby, methods always have access to the state of their associated instance.
In short, static
methods aren't really methods at all, they are procedures. Ruby doesn't have procedures, it only has (instance) methods.
There is no construct in Ruby that would even be remotely equivalent to Java's static
.
When you do
class MyClass
def self.do_something
# Do awesome stuff
end
end
self
merely refers to MyClass
. (Do class MyClass; puts self.inspect; end
if you don't believe me!) You can replace self
with MyClass
, or even something that refers to the class MyClass, and you'd have the same result.
You could do
class MyClass
end
foo = MyClass
def foo.do_something
# Do awesome stuff
end
and you'll get the same results.
And, you can do the same stuff on something that isn't a class
my_string = "HAI WORLD"
def my_string.do_something
# Yet more awesome stuff
end
and you can then call my_string.do_something
Would calling do_something
on my_string
be a static method?
So self
doesn't magically make a method static.
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