Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the equivalent to Lodash's get and set in Ruby?

Tags:

ruby

lodash

I would like to use something similar to Lodash's get and set, but in Ruby instead of JavaScript. I tried few searches but I can't find anything similar.

Lodash's documentation will probably explain it in a better way, but it's getting and setting a property from a string path ('x[0].y.z' for example). If the full path doesn't exist when setting a property, it is automatically created.

  • Lodash Set
  • Lodash Get
like image 874
e741af0d41bc74bf854041f1fbdbf Avatar asked Sep 25 '22 10:09

e741af0d41bc74bf854041f1fbdbf


2 Answers

I eventually ported Lodash _.set and _.get from JavaScript to Ruby and made a Gem.

like image 121
e741af0d41bc74bf854041f1fbdbf Avatar answered Sep 28 '22 04:09

e741af0d41bc74bf854041f1fbdbf


Ruby 2.3 introduces the new safe navigator operator for getting nested/chained values:

x[0]&.y&.z #=> result or nil

Otherwise, Rails monkey patches all objects with try(…), allowing you to:

x[0].try(:y).try(:z) #=> result or nil

Setting is a bit harder, and I'd recommend ensuring you have the final object before attempting to set a property, e.g.:

if obj = x[0]&.y&.z
  z.name = "Dr Robot"
end
like image 21
maniacalrobot Avatar answered Sep 28 '22 04:09

maniacalrobot