新手问题 ABC.new (:title=>"title",:flag=>"flag") 用 symbol 做参数是怎么实现的?

africwildman · 2015年01月07日 · 最后由 heylonj 回复于 2015年01月07日 · 1830 次阅读

如题。我试了一下搞不出来啊。

class Abc
  def initialize(opts = {})
    @title = opts[:title] || ""
    @flat = opts[:flag] || ""
  end
end

就是传了一个 hash

class ABC
  def initialize params
    p params
  end
end

这个不叫用 symbol 做参数,是个 hash 做参数,只是省略了大括号。

#1 楼 @huacnlee

class Abc
  def initialize title: '', flag: ''
    @title = title
    @flag = flag
  end
end

不是有这么个经典写法么

class Abc
  attr_accessor :title, :flag
  def initialize(opts = {})
    opts.each do |opt, value|
      send("#{opt=}", value)
    end
  end
end

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