Ruby exception occurred: can't convert String into Integer


(Sharon Sasporta) #1

Hi,

This is my Ruby filter code in logstash:

           message_array = event.get("message").split("\n\n[")
       	   message_array.each do | index |
       	         if index!=0
       	              event.set("Rule#{index}", "[" + message_array[index])
       	         end
       	   end

I am getting the error on run:

[2018-02-08T19:01:18,716][ERROR][logstash.filters.ruby ] Ruby exception occurred: can't convert String into Integer

The problem is in the line: event.set("Rule#{index}", "[" + message_array[index])

If I do as below, it works fine:

           event.set("Rule1", "[" + message_array[1])
       	   event.set("Rule2", "[" + message_array[2])

Can you pls help me to understand where the conversion from string to integer happens?

Thanks
Sharon.


(Paris Mermigkas) #2

In order to be able to iterate over an array's index you'll need each_index, not each.

So you generally have:
each |item| : iterates over items.
each_index |index| : iterates over indices.
each_with_index |item, index| : iterates over both.

As for the string to int error, it's probably due to some interpolation issue. Always try and explicitly convert types to avoid such pitfalls.

So the above would be:

message_array = event.get("message").split("\n\n[")
message_array.each_index do | index |
    if index!=0
        event.set("Rule"+index.to_s, "[" + message_array[index].to_s)
    end
end

or if you prefer one-liners for brevity,

message_array = event.get("message").split("\n\n[")
message_array.each_index { |index| event.set("Rule"+index.to_s, "[" + message_array[index].to_s) unless index == 0 }

(system) #3

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.