Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use .try function with .map function in ruby

Tags:

ruby

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.

like image 731
rubyist Avatar asked Jan 28 '15 09:01

rubyist


People also ask

What does .map do in Ruby?

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.

Does map return a new array Ruby?

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.

What is the difference between each and map in Ruby?

So each is used for processing an array and map is used to do something with a processed array.

What does &: mean in Ruby?

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.


1 Answers

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, ',')
like image 74
Marek Lipka Avatar answered Oct 21 '22 21:10

Marek Lipka