新手问题 self 下标访问

kingwkb · 2013年05月14日 · 最后由 boboism 回复于 2013年05月15日 · 2809 次阅读

看到代码可以 self[:xxx] 这样使用,请问这样和 self.xxx 有什么区别呢?

找不到 self 下标的资料

这个肯定是 ActiveRecord 里的功能吧,一般 Ruby 类不支持这种写法的

#1 楼 @iBachue 是的,model 里面的,这个实现在哪个文件?

#2 楼 @kingwkb puts method(:"[]").source_location

#2 楼 @kingwkb ActiveRecord 的 base.rb 文件

# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
# "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
# (Alias for the protected read_attribute method).
def [](attr_name)
  read_attribute(attr_name)
end

# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
# (Alias for the protected write_attribute method).
def []=(attr_name, value)
  write_attribute(attr_name, value)
end

#5 楼 @kingwkb 前面贴给你的是 2.3 的路径 ActiveRecord 3.2 的路径是 lib/active_record/attribute_methods.rb

# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
# "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
# (Alias for the protected read_attribute method).
def [](attr_name)
  read_attribute(attr_name)
end

# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
# (Alias for the protected write_attribute method).
def []=(attr_name, value)
  write_attribute(attr_name, value)
end

#6 楼 @iBachue 非常感谢,一直没没懂这个神马意思,现在终于懂了

self[:xxx] 是因为这个类实现了#[](*args)这个方法,实际上 self[:xxx] == self.[](:xxx)

需要 登录 后方可回复, 如果你还没有账号请 注册新账号