I am using Koala gem to get user permissions.
permissions = client.get_connections('me', 'permissions')
=> [{"permission"=>"installed", "status"=>"granted"}, {"permission"=>"public_profile", "status"=>"granted"},
{"permission"=>"read_stream", "status"=>"granted"},
{"permission"=>"email", "status"=>"granted"},
{"permission"=>"read_insights", "status"=>"granted"},
{"permission"=>"manage_pages", "status"=>"granted"},
{"permission"=>"user_friends", "status"=>"granted"}]
I would like to parse that response to get granted permissions in simple string like: "email, read_stream, read_insights, user_friends"
I thought about:
permissions.map {|h| puts h.fetch('permission') if h.fetch('status') == 'granted'}
Original suggestion of
permissions.map { |h| puts h.fetch('permission') if h.fetch('status') == 'granted' }
is close but has two issues, first already pointed out is superfluous puts
call. Second, as there probably may be values with status other than 'granted', the resulting array may contain nil
entries which need to be cleaned out before joining:
permissions.map { |h| h.fetch('permission') if h.fetch('status') == 'granted' }.compact.join(', ')
Actually this seems to be a valid case for the more obscure but slightly more efficient method which avoids walking the input twice:
permissions.each_with_object([]) { |h, a| a << h['permission'] if h['status'] == 'granted' }.join(', ')
You seem not to be using additional functionality Hash#fetch
provides so why not just use Hash#[]
?