Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split method name with regex and ruby

Tags:

regex

ruby

I would like to use a regex to get every variant of a method name like this:

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

I can do this with:

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

is it possible to have a arbitrary method length so we can have:

"my_very_special_specific_method" => ["my_very_special_specific_method", "very_special_specific_method", "special_specific_method", "specific_method", "method"]
like image 307
elsifaka Avatar asked Nov 23 '25 03:11

elsifaka


1 Answers

Here's one way:

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"]
like image 91
Casper Avatar answered Nov 24 '25 20:11

Casper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!