How can I create an array of all "name_printed" keys in the following hash with nil safe navigation?
{
"show_data_on_file": "Yes",
"employees_names_printed_on_badges": [
{
"name_printed": "John",
"badge_id": 12160060
},
{
"name_printed": "Tom",
"badge_id": 12160080
}
]
}
CodePudding user response:
You could use Enumerable#pluck
. In the case employees_names_printed_on_badges
returns a falsy value, you invoke pluck
on an empty array:
(data[:employees_names_printed_on_badges] || []).pluck(:name_printed)
# ["John", "Tom"]
Or use &
, which would result in nil if data[:employees_names_printed_on_badges]&
is nil.
data[:employees_names_printed_on_badges]&.pluck(:name_printed)