# Using a variable as an index of an array of patterns

**URL:** <https://discuss.elastic.co/t/using-a-variable-as-an-index-of-an-array-of-patterns/222617>\
**Category:** Logstash\
**Created:** [March 8, 2020, 6:42pm UTC](https://discuss.elastic.co/t/using-a-variable-as-an-index-of-an-array-of-patterns/222617 "2020-03-08T18:42:41Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![nino](https://avatars.discourse-cdn.com/v4/letter/n/b9bd4f/32.png) [@nino](https://discuss.elastic.co/u/nino)\
**Post date:** [March 8, 2020, 6:42pm UTC](https://discuss.elastic.co/t/using-a-variable-as-an-index-of-an-array-of-patterns/222617/1 "2020-03-08T18:42:41Z")

</div>

I have this filter in a logstash pipeline

```auto
filter{

    ruby { code => 'event.set("patternmatch1", event.get("message").scan(/TEXT.*?(\w[\w,.]*)\r?$/))'
    }
    # Retrieve the lenght of the array cointaining all the matches
    ruby { code => 'event.set("number_of_elements", event.get("patternmatch4").length-1)'
    }

```

**My goal**

I would like to use the array length as the index of a ruby array of patterns to choose index pattern that i want. Instead of using index 9:

```auto
mutate{
       add_field => {"gross_profit" => "%{[patternmatch4][9]}"}}
}

```

I want to reference the last pattern match of the array with the variable containing the lenght of the array "number\_of\_elements", but is not working. Maybe i am incorrectly referencing the variable. How to reference that variable correctly?

```auto
mutate{
   add_field => {"gross_profit" => "%{[patternmatch4][%{[number_of_elements]}"}}
}

```

---

<div class="post-metadata">

**Author:** ![Badger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/badger/32/25190_2.png) [@Badger](https://discuss.elastic.co/u/Badger)\
**Post date:** [March 8, 2020, 7:47pm UTC](https://discuss.elastic.co/t/using-a-variable-as-an-index-of-an-array-of-patterns/222617/2 "2020-03-08T19:47:22Z")

</div>

Depending on where you want use it, [arrayName][-1] may work.

---

<div class="post-metadata">

**Author:** ![nino](https://avatars.discourse-cdn.com/v4/letter/n/b9bd4f/32.png) [@nino](https://discuss.elastic.co/u/nino)\
**Post date:** [March 8, 2020, 8:39pm UTC](https://discuss.elastic.co/t/using-a-variable-as-an-index-of-an-array-of-patterns/222617/3 "2020-03-08T20:39:12Z")

</div>

> [@nino](#):
>
> mutate{ add\_field =\> {"gross\_profit" =\> "%{[patternmatch4][%{[-1]}"}} }

Thank you Badger,

[-1] is working perfectly

---

<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:** [April 5, 2020, 8:39pm UTC](https://discuss.elastic.co/t/using-a-variable-as-an-index-of-an-array-of-patterns/222617/4 "2020-04-05T20:39:16Z")

</div>

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