Reputation: 1006
Programming noob here. Just wondering what the best way to extract specific bits of information from a string is with Ruby.
I have some xml from an api that looks like this:
<users>
<user>
<twitter_screen_name>Jason</twitter_screen_name>
<kscore>81.78</kscore>
</user>
</users>
I just want to get the username and kscore out.
Heres what I've got, just wondering if theres a more efficient way?
info = Array.new
username = info[3].split('>')
username = username[1].split('<')
username = username[0]
klout = info[4].split('>')
klout = klout[1].split('<')
klout = klout[0]
Thanks
Upvotes: 0
Views: 102
Reputation: 178
Alternatively, you can use the Klout ruby wrapper, depending on what version you're using of Ruby.
This will work with < 1.8.6 : https://github.com/jasontorres/klout
This will work with >= 1.9.2 : https://github.com/mpautasso/klout (fork from the prior)
Upvotes: 0
Reputation: 434785
Use an XML parser such as Nokogiri:
doc = Nokogiri::XML(your_xml_string)
username = doc.at('twitter_screen_name').content
klout = doc.at('kscore').content.to_f
Trying to parse XML with regular expressions is not recommended.
Upvotes: 4