$1.to_sym => args[0]
和($1.to_sym,*args,&block)
在以下代码行中做了什么?ruby中的动态方法定义
class Table
def method_missing(id,*args,&block)
return as($1.to_sym,*args,&block) if id.to_s =~ /^to_(.*)/
return rows_with($1.to_sym => args[0]) if id.to_s =~ /^rows_with_(.*)/
super
end
# ...
end
语境:
Ruport是一个Ruby报表库。您可以使用Ruport ::数据表::类来创建表格数据,并将其转换为不同的格式文本,例如:
require 'ruport'
table = Ruport::Data::Table.new :column_names => ["country" , "wine" ], :data => [["France" , "Bordeaux" ], ["Italy" , "Chianti" ], ["France" , "Chablis" ]]
puts table.to_text
⇒
+--------------------+
| country | wine |
+--------------------+
| France | Bordeaux |
| Italy | Chianti |
| France | Chablis |
+--------------------+
比方说,你只选择了法国葡萄酒并将其转换为逗号分隔值:
found = table.rows_with_country("France")
found.each do |row|
puts row.to_csv
end
⇒
France, Bordeaux
France, Chablis
刚刚做的是在Ruport :: Data :: Table上调用名为rows_with_country()的方法。但是这个班的作者怎么知道你会有一个名为country的专栏?事实是,作者不知道这一点。如果你看看Ruport,你会发现rows_with_country()和to_csv()是Ghost方法。 Ruport :: Data :: Table类有点像上面定义的那样。
对rows_with_country()的调用变为调用更传统的 方法rows_with(:country),它将列名称作为参数-define- 。另外,对to_csv()的调用变成对as(:csv)的调用。如果方法 名称不以这两个前缀中的任何一个开头,则Ruport将返回 以引发NoMethodError的Kernel#method_missing()。 (这就是 super关键字是。)
简短回答:它将第一个匹配组并将其转换为符号,在本例中为“rows_with_”或“to_”尾随值,并将其作为方法参数传递,或将其用作散列键第一个参数为method_missing。 – 2012-07-10 13:05:33