IT박스

루비 셀프 키워드 사용?

itboxs 2020. 11. 26. 08:06
반응형

루비 셀프 키워드 사용?


self키워드에 대해 내가 이해 한 바에서 단순히 클래스의 현재 인스턴스를 나타냅니다. 이것은 항상 기본 동작이 아닙니까? 예를 들어, 아닙니다

self.var_one = method(args)그냥 var_one = method(args)?

그렇다면 self의 사용은 무엇입니까?


대부분의 경우 동일한 효과를 위해 self.foo쓸 수 있기 때문에 실제로 중복 foo되지만이 경우에는 self필요 하지 않습니다.

var_one = method(args)라는 지역 변수를 생성합니다. var_one어떤 메서드도 호출하지 않거나 다른 작업을 수행하지 않습니다 self.

self.var_one = method(args)인수 var_one=self사용하여 on 메서드 호출합니다 method(args).

의 사용이 self선택 사항이 아닌 또 다른 경우 는 메서드에 인수로 전달하려는 경우입니다. 즉 some_method(self), self키워드 없이는 수행 할 수 없습니다 .


몇 가지 중요한 용도가 있으며, 그 중 대부분은 기본적으로 인스턴스 메서드, 클래스 메서드 및 변수를 명확하게하기위한 것입니다.

첫째, 이것이 클래스 메서드를 정의하는 가장 좋은 방법입니다. IE :

class Foo
  def self.bar
    "class method bar"
  end

  def bar
    "instance method bar"
  end
end

Foo.bar  #returns "class method bar"

foo = Foo.new
foo.bar #returns "instance method bar"

또한 인스턴스 메서드에서 self는 인스턴스를 참조하고, 클래스 메서드에서는 클래스를 참조하며, 항상 지역 변수와 구별하는 데 사용할 수 있습니다.

class Bar
  def self.foo
    "foo!"
  end

  def baz
    "baz!"
  end

  def self.success
    foo #looks for variable foo, doesn't find one, looks for class method foo, finds it, returns "foo!"
  end

  def self.fail
    baz #looks for variable baz, doesn't find one, looks for class method baz, doesn't find one, raises exception
  end

  def instance_success
    baz #looks for variable baz, doesn't find one, looks for instance method baz, finds it, returns "baz!"
  end

  def instance_fail
    foo #looks for variable foo, doesn't find one, looks for instance method foo, doesn't find one, raises exception
  end

  def local_variable
    baz = "is my favorite method"
    baz #looks for variable baz, finds it, returns "is my favorite method"
  end

  def disambiguate
    baz = " is my favorite method"
    self.baz + baz #looks for instance method baz, finds it, looks for local variable baz, finds it, returns "baz! is my favorite method"
  end
end

So, in the end, you can avoid using self in many cases, but it's often helpful to go ahead and use it to make sure that you don't inadvertently create naming conflicts later on. Sometimes those can create bugs that are very hard to find. In the end it's often a matter of personal style.


Update: As noted in the comments, one more really important thing:

In a class, if you have a method like this:

def bar=(string)
  ...
end

And in another method you call:

def other_method
  bar = "abcd"
end

It isn't going to call your bar= method, it's going to create a local variable bar. So, in this case you use self to tell ruby not to create a local variable, like so:

def other_method
  self.bar = "abcd"
end

The same thing applies if you want to take an argument with the name of a method, like so:

def example
  ...
end

def other_thing(example)
  self.example(example)
end

If you left off self it would assume you meant the local variable with the same name.

So, in general, self in method names is used to distinguish between class and instance variables, and everywhere else you use it when Ruby needs help distinguishing between method calls and local variables or local variable assignment.

I hope that makes sense!


here's an example use:

def run miles
  self.miles = miles
end

In this case self will help. in most cases self is redundant.


One other use of self is to declare class methods (similar to static methods in Java).

class foo
 def self.bar
  #do class related stuff here
 end
end

That being said, you could also have used def foo.bar instead for the method signature.

참고URL : https://stackoverflow.com/questions/6669527/use-of-ruby-self-keyword

반응형