Trying to combine an array of value

Hello, I have an array like this:

  "address": {
    "line1": "X",
    "line2": "Y",
    "line3": "Z"

I’m trying to get a resulting hash: { "address_line1": "X Y Z" }. I can’t figure out how to combine the different-keyed value. extract_key requires the key name to be the same, wrap and nest don’t exactly offer what I want.

I’m new to dry-rb so I’m getting a bit brain-knotted, can someone help me out?


I have two difficulties with your question: 1. you mention an array, but your example doesn’t have one, 2. you did not specify what library you’re talking about so it took several readings to deduce you’re using dry-transformer.

So, your first problem is that you’re confusing data types. extract_key is for Arrays, and you’re working with Hashes.

Given the input and output you have defined, it would look like this

#!/usr/bin/env ruby
# frozen_string_literal: true

require 'bundler/inline'

gemfile do
  source ''
  gem 'dry-transformer'

require 'dry/transformer'

class AddressTransformer < Dry::Transformer::Pipe
  import Dry::Transformer::HashTransformations

  define! do
    map_value :address, ->(a) { a.values_at(:line1, :line2, :line3).join(" ") }
    rename_keys address: :address_line1

  address: {
    line1: "X",
    line2: "Y",
    line3: "Z"

which outputs:

{ :address_line1 => "X Y Z" }
1 Like

Thank you!

You’re right, sorry for the dreadful examples I was a bit braindead.

I ended up solving it similarily:

          nest :address_line1, %i[ligne2 ligne3 ligne4 ligne5 ligne6 ligne7]

          map_value :address_line1, ->(hash) { hash.values.compact.join(" ") }

which is pretty close! But I’m also noting the awesome everything-in-one-file test case reproduction, thank you.