naming methods as variables calling methods Ruby

折月煮酒 提交于 2019-12-13 05:06:47

问题


hi i am very much a beginner.

i think i understand how the attr_accessor works (below). and the "setter" is the name=(name) method. and i know that that method is equivalent to the assignment: name = "john". because "=" is a method that accepts an argument and assigns that argument to whatever object calls it. (though i don't understand how "name" could be considered an object as it is being assigned to an object)

so my question is: how can you assign a variable calling a method as a method name? It feels like I'm missing something..

class Person
  def name
    @name
  end

  def name=(name)
    @name = name
  end
end

回答1:


so my question is: how can you assign a variable calling a method as a method name? It feels like I'm missing something..

You don't. In this code

def name=(name)
  @name = name
end

name= isn't a variable name calling a method =. The name of the method is name=.

Edit:

In the above code snippet the def paired with a terminating end constitutes a method definition.

def method_name(param1, param2)
  # method body
end

On the same line as def there can only be the method name, optional parentheses, and the param list. By definition having a "variable calling a method" in that line would be illegal. So in your code name= is the method name.



来源:https://stackoverflow.com/questions/20932032/naming-methods-as-variables-calling-methods-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!