运维开发网

在Ruby中,有什么方法可以过滤包含“time”一词的对象的所有方法?

运维开发网 https://www.qedev.com 2020-07-25 22:03 出处:网络 作者:运维开发网整理
我尝试了以下内容,部分工作: >> s.methods.map {|n| n if n =~ /time/} => [nil, nil, nil, nil, nil, nil, nil, nil, "skip_time_zone_conversion_for_attri butes", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, n
我尝试了以下内容,部分工作:

>> s.methods.map {|n| n if n =~ /time/}
=> [nil, nil, nil, nil, nil, nil, nil, nil, "skip_time_zone_conversion_for_attri
butes", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, ni
l, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, ni
l, "timestamped_migrations", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, n
il, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, n
il, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, n
il, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, n
il, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, "time_zone_aware
_attributes", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, n
il, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, "default_timezone", nil, n
il, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, n
il, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, n
il, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, n
il, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, "recor
d_timestamps", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil]

>> s.methods.each {|n| p n if n =~ /time/}
"skip_time_zone_conversion_for_attributes"
"timestamped_migrations"
"time_zone_aware_attributes"
"default_timezone"
"record_timestamps"
=> ["extended_by", "before_create", "vote_ids=", "save_without_dirty", "_delete"
, "touch", "daemonize", "after_destroy", "skip_time_zone_conversion_for_attribut
es", "methods", "send", "to_query", "becomes", "after_validation", "store_full_s
ti_class?", "save_with_transactions!", "autosave_associated_records_for_votes",
"require_library_or_gem", "enum_for", "taint", "instance_variable_defined?", "ac
     [...] and the rest of the whole array

>> s.methods.filter {|n| n =~ /time/}
NoMethodError: undefined method `filter' for #<Array:0x4de6b00>
        from (irb):93
grep是实现此目的的另一种简单方法:

1.9.0 > require 'date'
 => true 
1.9.0 > x = Date.new
 => #<Date: -1/2,0,2299161> 
1.9.0 > x.methods.grep /time/
 => ["ctime", "asctime", "strftime"]

使用您尝试的方法:

map将给定块应用于给定枚举的每个元素,返回一个新的可枚举.这不是你想要的(正如你所看到的).

方法也是一种工作,但显然只是打印出结果并不是非常有用.它根本不像Ruby,但你可以做到:

matching_methods = []
s.methods.each {|m| matching_methods << m if m =~ /time/}

将匹配/时间/匹配的每个方法累积到matching_methods数组中.当然,如果你这样做,那么

s.methods.select { |m| m =~ /time/ }

是优选的.

最后,Ruby中不存在过滤器;这就是select(或find_all)的用途.

0

精彩评论

暂无评论...
验证码 换一张
取 消