I need to get some values from the json record and extracting like below
curr_json_doc['title']['genre'].map { |s| s['name'] }.join(',')
But for some records curr_json_doc['title']['genre'] can be blank. So I want to use try function for map and join().
I tried like below
curr_json_doc['title']['genre'].try(:map, { |s| s['name'] }).try(:join, (','))
but it didnt work.
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
Applying map on an array returns a new array where each element is the result of evaluating the block with the element as an argument. As you can see, the block plays the role of the function in Ruby.
So each is used for processing an array and map is used to do something with a processed array.
In a method argument list, the & operator takes its operand, converts it to a Proc object if it isn't already (by calling to_proc on it) and passes it to the method as if a block had been used.
You don't pass block correctly. Blocks are passed to methods outside argument parenthesis:
curr_json_doc['title']['genre'].try(:map) { |s| s['name'] }.try(:join, ',')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With