Can a ruby ​​trigger be used as a filter to make kludgy smaller?

To get some of the text, I use kludge true ifbefore the trigger:

desired_portion_lines = text.each_line.find_all do |line|
  true if line =~ /start_regex/ .. line =~ /finish_regex/
end
desired_portion = desired_portion_lines.join

If I remove the bit true if, he complains

Bad value for range (ArgumentError)

Is it possible to make it less shabby, or just I have to do

desired_portion_lines = ""
text.each_line do |line|
  desired_portion_lines << line if line =~ /start_regex/ .. line =~ /finish_regex/
end

Or is there a better approach that does not use enumeration?

+3
source share
3 answers

if you do it line by line, my preference is something like this

line =~ /finish_regex/ && p=0
line =~ /start_regex/ && p=1
puts line if p

if you have everything on one line. I would use split

mystring.split(/finish_regex/).each do |item|
  if item[/start_regex/] 
     puts item.split(/start_regex/)[-1]
  end
end
+1
source

I think,

desired_portion_lines = ""
text.each_line do |line|
  desired_portion_lines << line if line =~ /start_regex/ .. line =~ /finish_regex/
end

. .. , , , , , . , , , . Perl, , , .

, -, :

desired_portion_lines = ""
text.each_line do |line|
  desired_portion_lines << line if ( (line =~ /start_regex/) .. (line =~ /finish_regex/) )
end

Ruby ( Perl), , , . , , .

, , desired_portion_lines . desired_portion_lines << line , . , , , .

. , , :

desired_portion = text.each_line.find_all { |line| line =~ /start_regex/ .. line =~ /finish_regex/ }.join

, , , desired_portion.

+1

You can save three characters by replacing true ifwith !!()(with a flip flop between parentheses).

0
source

Source: https://habr.com/ru/post/1793482/


All Articles