0

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

mu is too short
  • 426,620
  • 70
  • 833
  • 800
AFraser
  • 996
  • 4
  • 13
  • 27
  • Obligatory amusing "Don't parse XML yourself" link: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Andrew Grimm Sep 08 '11 at 05:37

2 Answers2

4

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
0

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)

harmophone
  • 178
  • 5