Home > front end >  Ruby on Rails concatenate key & values
Ruby on Rails concatenate key & values

Time:11-25

I have the following array:

[
  {
    "name_printed_on_badge": "John",
    "is_active": "Yes",
    "is_valid": "Yes"
  },
  {
    "name_printed_on_badge": "John",
    "is_active": "Yes",
    "is_valid": "No"
  }
]

I want to learn how to concatenate each key and value pair and return an array in the output format below:

[
  [
    "name_printed_on_badge: John",
    "is_active: Yes",
    "is_valid: Yes"
  ],
  [
    "name_printed_on_badge: John",
    "is_active: Yes",
    "is_valid: No"
  ]
]

CodePudding user response:

array = [
  {
    "name_printed_on_badge": "John",
    "is_active": "Yes",
    "is_valid": "Yes"
  },
  {
    "name_printed_on_badge": "John",
    "is_active": "Yes",
    "is_valid": "No"
  }
]

array.map do |hash| 
  hash.map { |key, value| "#{key}: #{value}" }
end
# [["name_printed_on_badge: John", "is_active: Yes", "is_valid: Yes"], ["name_printed_on_badge: John", "is_active: Yes", "is_valid: No"]]
  • Related