There is a variable with a bunch of rows, I want to get the value 123123123 in a separate variable, I write:

 out = "app_ver = 1.4.8 arp_inspection = 123123123 arp_inspection_errors = 0 clients_count = 0 ip_guard_errors = 0 non_client_bw_limit_down = 5242880 non_client_bw_limit_up = 5242880 session_unauth_count = 0 sessions_count = 0 start_time = 1454235448" out.each_line do |line| if (line =~ /[arp_inspection]*([0-9])/) then arp_inspection = line end end print arp_inspection 

What am I doing wrong? How do I get the value of arp_inspection out?

    3 answers 3

    You can do a direct assignment of a variable to a value from within Regexp :

     /^arp_inspection =.*(?<arp_inspection>[0-9])/ =~ line # arp_inspection => 123123123 

    Note that the main thing is not to change the Regexp and the string in some places, otherwise the assignment will not happen, and it works only for Ruby 1.9.1 and higher, if I'm not mistaken.

       out = "app_ver = 1.4.8 arp_inspection = 0 arp_inspection_errors = 0 clients_count = 0 ip_guard_errors = 0 non_client_bw_limit_down = 5242880 non_client_bw_limit_up = 5242880 session_unauth_count = 0 sessions_count = 0 start_time = 1454235448" arp_inspection = "123123123" out.each_line do |line| line = line.chomp if (line =~ /^arp_inspection =.*([0-9])/) then print $1, "\n" arp_inspection = $1 end end print arp_inspection 
      • Tell me, is this the answer or addition to the question? - Nicolas Chabanovsky
      • Nicolas Chabanovsky, I have already found a solution. This way it works. The error was in the regular season. - nobody

      The variable is not "a bunch of lines", but one line, but with the presence of newline characters ( \n ). Therefore, the result is not a cycle, but one operation:

       arp_inspection = out[/^arp_inspection = (\d*)/, 1]