# Getting length of array in Logstash using ruby filter

**URL:** https://discuss.elastic.co/t/getting-length-of-array-in-logstash-using-ruby-filter/151999
**Category:** Logstash
**Created:** [October 11, 2018, 7:36am UTC](https://discuss.elastic.co/t/getting-length-of-array-in-logstash-using-ruby-filter/151999 "2018-10-11T07:36:54Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![dx123](https://avatars.discourse-cdn.com/v4/letter/d/d9b06d/32.png) [@dx123](https://discuss.elastic.co/u/dx123)
#### Post date: [October 11, 2018, 7:36am UTC](https://discuss.elastic.co/t/getting-length-of-array-in-logstash-using-ruby-filter/151999/1 "2018-10-11T07:36:54Z")

</div>

I have a field, Ports, that is in arrays and is nested.

**Examples of my data**  
"ports": ["TCP1", "TCP2", 'TCP3"]  
"ports": ["UDP1", "UDP2"]

However each of these feeds have different number of elements in them. I have to strip the array brackets through the mutate replace filter but before that I need a ruby filter to retrieve the number of elements for each feed for a if-else check.

Desired Output:

```
filter {
     ruby {
         code => ??? Need help here with the code
     }
 
      mutate {
          if [number of elements] == 3 {
              replace => ["ports", "%{[port][0]} %{[port][1]} %{[port][2]}"]
          }
          else if [number of elements] == 2 {
              replace => ["ports", "%{[port][0]} %{[port][1]}"]
          }
        }
      }
```

---

<div class="post-metadata">

### Author: ![paz](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/paz/32/28003_2.png) [@paz](https://discuss.elastic.co/u/paz)
#### Post date: [October 11, 2018, 10:20am UTC](https://discuss.elastic.co/t/getting-length-of-array-in-logstash-using-ruby-filter/151999/2 "2018-10-11T10:20:46Z")

</div>

To get the length of an array you can use this

```auto
ruby {
  code => "
    event.set('number_of_elements', event.get('ports').length)
  "
}
```

That said, if you just need to flatten the array and keep the information inside as a string, you can do the following instead of the whole conditional of your post (which removes the need for counting array lengths and the mutate filter).

```auto
ruby {
  code => "
    event.set('ports', event.get('ports').join(' '))
  "
}
```

This would convert

> "ports": ["TCP1", "TCP2", 'TCP3"]

to

> "ports": "TCP1 TCP2 TCP3"

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [November 8, 2018, 10:34am UTC](https://discuss.elastic.co/t/getting-length-of-array-in-logstash-using-ruby-filter/151999/3 "2018-11-08T10:34:13Z")

</div>

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