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

后端 未结 3 1492
梦如初夏
梦如初夏 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:41

    Following this tutorial, you have no need to use self pointer. But i think this (or self in our case) pointers are used to resolve name conflicts. Actually, @name and self.name are the same statements (if there is no name method for your class). E.g.:

    class Moo
      attr_accessor :name
    
      def moo(name)
        name = name # O_o which *name* should i use?
      end
    
      def foo(name)
        @name = name # the same as *self.name = name*
      end
    
      def hello
        puts self.name # the same as *puts @name*
      end
    end
    
    a = Moo.new
    a.hello() # should give no output
    
    a.moo('zaooza')
    a.hello() # Hey! Why does it prints nothing?
    
    a.foo('zaooza')
    a.hello() # whoa! This one shows 'zaooza'!
    

    Try running this code and you'll see =)

提交回复
热议问题