In Ruby, is self.user_name the same as @user_name?

In Ruby, is not a type instance @foovariable and a class variable @@bar?

In some code, I see several

self.user_name = @name

or even

a += 1 if name != user_name   # this time, without the "self."
                              # and it is the first line of a method so 
                              # it doesn't look like it is a local variable

what is it for? I thought it could be an accessor, but could it just be user_name instead of self.user_name? And I don’t even see any code to make it an accessor, for example attr_accessor, and not in the base class.

+3
source share
3 answers

In Ruby:

  • @foo is an instance variable
  • @@bar is a class variable

By default, instance and class variables are private. This means that you cannot set or get a value outside the class or the module itself.

foo, .

class Model
  def foo
    @foo
  end

  def foo=(value)
    @foo = value
  end
end

( ) ,

class Model
  attr_accessor :foo
end

m = Model.new
m.foo = "value"

doo

class Model

  # ...

  def something
    self.foo = "value"
    # equivalent to
    @foo = value
  end

end
+4

? ,

- , . self.name = something name= self.name, , name, , name name.

user_name self.user_name?

name= self, name = something name. name , name self.name, name.

, , attr_accessor, .

attr_accessor name name= , method_missing , attr_accessor.

self.user_name , @user_name

. user_name user_name=? using attr_accessor they will get and set @user_name`. , ( ), , .

, ActiveRecord method_missing getter setter, . , ActiveRecord user_name, user_name user_name=, . , user_name user_name =, . @user_name.

user_name user_name= Struct:

MyClass = Struct.new(:user_name)

MyClass user_name user_name=, @user_name ​​ .

+1

"scope"!

, , , .

:

class Woot
  attr_accessor :name

  def initialize
    self.name = 'Bistromathic Drive'
  end

  def foo
    puts name # hum… I don't know name. An attr? Oh Yes!
    name = '42' # New local var named 'name'
    puts name # Yeah! I know a local named 'name'
    puts self.name # I know the attr named 'name'
    name = 'Improbability Drive' # Change the local
    puts name 
    puts self.name # attr didn't move
    self.name = 'What was the question?'
    puts name
    puts self.name
  end
end
w = Woot.new
w.foo
# => Bistromathic Drive
42
Bistromathic Drive
Improbability Drive
Bistromathic Drive
Improbability Drive
What was the question?

The partial code that you show is β€œsuspicious” to me, and I would rather explain the base of the var region.

-1
source

Source: https://habr.com/ru/post/1770851/


All Articles