Defining range using regular expressions in Ruby on Rails -
this question has answer here:
i have code:
(1..40).map(&:to_s).grep(/[2-3][0-9]/)
so when type in [2-3][0-9]
print numbers in range (which between 20 , 39). how can without defining range (i.e. in case "1..40") works regular expression type brackets?
so similar code
(1..40).map(&:to_s).grep(/[2-3][0-9]/)
that work without (1..40).map
part.
ok, awful, , don't want this, think do. but, fwiw:
def this_is_awful(string) results = [] string.split("|").each |section| #example section "5[0-3][2-4]" section_digits = [] section.split(/[\[\]]+/).select{|s| s.size > 0}.each |range_string| range_digits = range_string.split("-").select{|s| s.size > 0} arrays = (range_digits[0]..range_digits[-1]).to_a section_digits << arrays if arrays.size > 0 end #now need every combination of these section_digits[0].product(*section_digits[1..-1]).each |combination| results << combination unless results.include?(combination) end end #at point, results [[5, 0, 2], [5, 0, 3], [5, 0, 4], etc]. sort these , convert them digits via strings results.sort.collect{|arr| arr.join} end
eg
irb(main):075:0> this_is_awful("5[2-3]") => [52, 53] irb(main):076:0> this_is_awful("5[2-3][3-9]") => [523, 524, 525, 526, 527, 528, 529, 533, 534, 535, 536, 537, 538, 539] irb(main):077:0> this_is_awful("5[2-3][3-9]|10[1-7][3-8]") => [523, 524, 525, 526, 527, 528, 529, 533, 534, 535, 536, 537, 538, 539, 1013, 1014, 1015, 1016, 1017, 1018, 1023, 1024, 1025, 1026, 1027, 1028, 1033, 1034, 1035, 1036, 1037, 1038, 1043, 1044, 1045, 1046, 1047, 1048, 1053, 1054, 1055, 1056, 1057, 1058, 1063, 1064, 1065, 1066, 1067, 1068, 1073, 1074, 1075, 1076, 1077, 1078]
btw question has nothing ruby on rails.
edit: edited work more generally, enumerable (so work letters example). strings can convert them integers if want .collect(&:to_i)
eg
irb(main):122:0> this_is_awful("a[b-e][f-g]") => ["abf", "abg", "acf", "acg", "adf", "adg", "aef", "aeg"]
edit 2: fixed bug when starts array
Comments
Post a Comment