view raw
YoYoYo I'm Awesome YoYoYo I'm Awesome - 9 months ago 30
Ruby Question

Grabbing digits from a string and using those digits to grab from a yaml file

I'm trying to grab integers out of a string and use those integers to scan through a YAML file like so:

FORMS = YAML.load_file('../email/lib/lists/form_links.yml')

def get_form(form)
form_num = form.scan(/\d+/)
data = FORMS['esd_forms'][form_num]
if data != nil
"Form link: #{data}"
raise StandardError
rescue StandardError
"** Form: #{form} is not a valid form name **"

YAML file:

1: ''
2: ''
3: ''
4: ''
5: ''
6: ''
7: ''
8: ''
9: ''
10: ''
11: ''
03: ''
07: ''
10: ''
13: ''
14: ''

When I do this I get an error:

wrong argument type Array (expected Regexp)

I don't understand why I'm getting that error? At first I thought it was because the program was returning an array instead of a string so I tried it in IRB:

irb(main):001:0> form = 'esd-2'
=> "esd-2"
irb(main):002:0> form_num = form.scan(/\d+/)
=> ["2"]
irb(main):003:0> puts form_num

To me it seems like I'm doing this correctly, what am I doing wrong?


String#scan returns all the occurrences in the String that matches the regular expression, in an array.

You see in your irb session when you execute form_num = form.scan(/\d+/), it actually returns an array with 1 element ["2"].

If you want to return the first matched segment, you can use String#[]:

form = 'esd-2'
form_num = form[/\d+/]
#=> "2"

Besides, if you need to examine what is stored in an variable, p will be a better choice than puts. And irb actually use p to output the expression result by default as you see in your irb session.

form = 'esd-2'
form_num = form.scan(/\d+/)
puts form_num
#=> 2
p form_num
#=> ["2"]