新手问题 定义方法后面加 “=”,意义是什么?

drine · March 13, 2015 · Last by rubyyjc520 replied at May 30, 2019 · 4007 hits

def current_user=(user) @current_user = user end

不明白为什么这样做,能稍微讲解一下?感谢了!!!

网上找了下现有的资料看了,但还是没明白这么做的意义到底体验在何处。

getter setter

本质作用就是各种赋值、取值的事件 hook

class AttrReader
  attr_reader :attr_ar
end
p AttrReader.new.methods.grep(/attr/)

class AttrWriter
  attr_writer :attr_aw
end
p AttrWriter.new.methods.grep(/attr/)

class Attr
  attr_accessor :attr
end
p Attr.new.methods.grep(/attr/)

这里是赋值方法,可以带 = ! ?

楼主的例子中,定义方法是为了封装@current_user,不要暴露实例变量

#5 楼 @loveltyoic 我想知道调用这个方法的时候调用过程是什么样的..

就是 java 里面的 setter

看了上面的回答..感觉理解起来还是有点力不从心 :(

#6 楼 @drine

current_user = User.find(params[:user_id])

#9 楼 @loveltyoic 谢谢,再试着理解下。

楼主没有清楚表达他不明白哪一点,所以回复的人从 Ruby 基础到架构设计都回答了一轮,然后楼主觉得哇怎么这么深奥。

#12 楼 @Rei 我觉得他已经表达清楚了,题目里就问的是针对方法名后面的=

#11 楼 @blacktulip 其实以等号结尾的方法有特殊处理:

def current_user=(user)
  @xx = user
  nil
end

和下面不一样

def set_current_user(user)
  @xx = user
  nil
end

current_user(user) 的返回值永远是 user set_current_user(user) 的返回值是 nil

#14 楼 @hooooopo 果然是这样,谢谢指正。我测试了一下,带等号的方法只能接受一个参数,这应该也是个特殊处理。这种方法的返回值永远是接受的那个参数,我猜测。

def current_user=(user, another)
  @current_user = user + another
  nil
end

current_user=("test", "other")
=>
SyntaxError: syntax error, unexpected ',', expecting ')'
current_user=("test", "other")
                     ^
    from /Users/blacktulip/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'

#16 楼 @eddie 赞,有老师上课的风范

#16 楼 @eddie 这么讲就清晰很多啦!谢谢楼上各位~!

Catherine in 关于以=结尾的方法 mention this topic. 30 Sep 09:13
Reply to eddie

醍醐灌顶,感谢!

Rei in Ruby 中传参的问题 mention this topic. 01 Dec 13:10
You need to Sign in before reply, if you don't have an account, please Sign up first.