I have an hash array as shown below:
sample = {:a=>1, :b=>2, :c=>{:c1=>abc, :c2=>xyz}, :d=>3}
And my desired output is:
1|2|abc|xyz|3
But if I use the command: sample.values.join("|")
My output is getting displayed as below:
1|2|c1abcc2xyz|3
Please help me out with this query. Thanks in advance.
sample.values.flat_map { |x| x.is_a?(Hash) ? x.values : [x] }.join("|")
#=> "1|2|abc|xyz|3"
To handle arbitrary depth, you need to use recursion, like this:
def nested_values(object)
object.values.reduce([]) do |array, value|
array + (value.is_a?(Hash) ? nested_values(value) : [value])
end
end
sample = {:a=>1, :b=>2, :c=>{:c1=>:abc, :c2=>:xyz}, :d=>3}
p nested_values(sample).join("|")
Output:
"1|2|abc|xyz|3"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With