Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use the dig method to get the last element of an array?

Tags:

arrays

ruby

hash

Lets say I have the following:

nested_object = [0, 1, 2, {foo: 'bar'}]

How do I use dig to select the last element of the array as I search for deeper nested objects?

like image 529
Nick Gronow Avatar asked Nov 01 '16 16:11

Nick Gronow


1 Answers

A negative value integer in any dig method arguments starts at the end of the array and moves towards the beginning. So -1 selects the last element of the array, -2 selects the second from last, and so on. So, in your case:

target = nested_object.dig(-1, :foo)

will select the last element of the array and proceed from there.

like image 103
Nick Gronow Avatar answered Nov 11 '22 22:11

Nick Gronow