新手问题 Ruby 新手求答疑

Thomas_Ruby · April 08, 2016 · Last by qinfanpeng replied at April 12, 2016 · 1717 hits

有一个类 它的属性写成如下: attr_accessor *%w(id level alt_id intersection_of replaced_by created_by creation_date disjoint_from relationship name namespace def subset comment is_obsolete synonym xref consider is_a).map(&:to_sym)

请问是啥意思啊 正则表达式吗

把数组中的每个字符串转化为符号,再将这个数组展开为 attr_accessor 的参数列表

%w(a b c) 相当于 ["a", "b", "c"] %w(a b c).map(&:to_sym) 相当于 [:a, :b, :c]

打开 irb,把后面那串输入运行看看结果。

这里可以看成三步处理:

%w(id level) => ["id", "level"]
["id", "level"].map(&:to_sym) => [:id, :level]
attr_accessor *[:id, :level] 相当于 attr_accessor :id, :level

zhengpd 解释得很有耐心、很详细了,不过还可以直接 %i(id level) => [:id, :level],如此就不用再 map(&:to_sym)

You need to Sign in before reply, if you don't have an account, please Sign up first.