When to use `self.foo` instead of `foo` in Ruby methods

后端 未结 3 1491
梦如初夏
梦如初夏 2020-11-27 04:22

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
    p         


        
3条回答
  •  余生分开走
    2020-11-27 04:58

    If you omit self Ruby will first look for local variables with that name, then for an instance method. It's not idiomatic to write self.. In any case, you have to write self.something = value on assignations.

    Note that you cannot use self when calling private methods (no problem with protected methods):

    class A
      def foo; self.bar; end
    
    private
    
      def bar; "bar"; end
    end
    
    A.new.foo  
    # private method `bar' called for # (NoMethodError)
    

提交回复
热议问题