Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print hash values with pipe separated

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.

like image 961
kattashri Avatar asked Dec 22 '25 10:12

kattashri


2 Answers

sample.values.flat_map { |x| x.is_a?(Hash) ? x.values : [x] }.join("|")
#=> "1|2|abc|xyz|3"
like image 50
tokland Avatar answered Dec 24 '25 02:12

tokland


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"
like image 30
Dogbert Avatar answered Dec 24 '25 03:12

Dogbert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!