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

1 つの方法を次に示します。

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_variants = [method_name]
while last = method_name_variants.last.split("_", 2)[1]
    method_name_variants.push(last)
end
于 2012-09-09T13:38:38.220 に答える
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 に答える
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 に答える
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 に答える