2

我想使用正则表达式来获取方法名称的每个变体,如下所示:

method_name = "my_special_title"
method_name_variants = ["my_special_title", "special_title", "title"]

我可以这样做:

r = /((?:[^_]*_)?((?:[^_]*_)?(.*)))/
r.match("my_special_title").to_a.uniq
=> ["my_special_title", "special_title", "title"]

是否可以有任意的方法长度,所以我们可以有:

"my_very_special_specific_method" => ["my_very_special_specific_method", "very_special_specific_method", "special_specific_method", "specific_method", "method"]
4

7 回答 7

5

这是一种方法:

s = "my_very_special_specific_method"
a = s.split('_')
a.length.times.map { |n| a.from(n).join('_') }

=> ["my_very_special_specific_method", "very_special_specific_method", 
    "special_specific_method", "specific_method", "method"]
于 2012-09-09T12:21:38.973 回答
2

我会这样做:

method_name = "my_special_title"
parts = method_name.split('_')
arr = []
(0..parts.length-1).each { |i| arr << parts[i..-1].join('_') }
于 2012-09-09T12:17:12.267 回答
2
method_name_variants = [method_name]
while last = method_name_variants.last.split("_", 2)[1]
    method_name_variants.push(last)
end
于 2012-09-09T13:38:38.220 回答
0
def my_method (str,split_by,join_by)
    results = Array.new    
    arr = str.send(:split,split_by)
    arr.count.times do |element|
    results << arr.send(:join,join_by) unless arr.blank?
   arr.pop
 end
results
end

呼叫人

my_method("my_special_title",'_','_')
于 2012-09-09T12:22:30.190 回答
0

"very_special_name".split /_/=>["very","special","name"]然后重新组装怎么样:

method_name = "my_very_special_method_name"
(*pref, base) = method_name.split /_/
a = [base]
pref.reverse.each do |prefix|
    a << (prefix + "_" + a[-1])
end
于 2012-09-09T12:27:44.740 回答
0

在一行中:

str = "my_very_special_specific_method"
str.split('_').reverse.reduce([]){|acc, s| acc << s+'_'+acc.last.to_s}.reverse.map!{|s| s[0..-2]}
于 2012-09-09T12:30:05.443 回答
0
a = "some_method_name".split '_'
a.map {|element| a[(a.index element)...a.length].join '_' }

# => ["some_method_name", "method_name", "name"]
于 2012-09-09T23:04:02.397 回答