简体   繁体   中英

Ruby array printing

I have an array of objects ( nokogiri xml nodes ) and each node is having name and value . I want to print them in the format name=value without iterating in for loop.

if I use arr * "," I'm able to see just the values as below

4900.00,5.00,0.00,-100.00,100.00
6085.00,5.00,1285.00,1185.00,100.00
6015.00,5.00,30.00,-70.00,100.00
5915.00,5.00,0.00,-100.00,100.00
5815.00,5.00,0.00,-100.00,100.00

Is there something that can be done here.

Something like this should work:

array.each do |n|
  puts "#{n.name}=#{n.value}"
end

Assuming that your Nokogiri nodes have name and value attributes (not child elements), here's one way:

# Convert the array into a new array of strings
namevals = my_array.map{ |node| "#{node['name']}=#{node['value']}" }

# See it with space delimiters
puts namevals.join(' ')

Possibly useful alternative:

# Create a hash mapping unique names to values
namevals = Hash[ my_array.map{ |node| [ node['name'], node['value'] } ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM