This is not specific for Rails - I am just using Rails as an example.
I have a model in Rails:
class Item < ActiveRecord::Base def hello puts "Hello, #{self.name}" end end
(Let's assume that the Item
model (class) has a method called name
.) When do I need to use self.name
and when can I just use name
(e.g., #{name}
)?
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.
You could define method in any order, the order doesn't matter anything.
A method in Ruby is a set of expressions that returns a value. With methods, one can organize their code into subroutines that can be easily invoked from other areas of their program. Other languages sometimes refer to this as a function. A method may be defined as a part of a class or separately.
It is idiomatic to prefer to omit self.
when invoking methods; it is generally never needed.
You must use self.foo = xxx
when calling a setter method, instead of foo = xxx
, so that Ruby realizes that you are not trying create a new local variable.
do_something
with the same name as a method, you must use self.do_something
to invoke the method, as just do_something
will end up reading the variable.You cannot use self.foo(...)
to call a private method; you must instead call just foo(...)
.
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