YoYoYo I'm Awesome YoYoYo I'm Awesome - 3 months ago 10
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]
begin
if data != nil
"Form link: #{data}"
else
raise StandardError
end
rescue StandardError
"** Form: #{form} is not a valid form name **"
end
end


YAML file:

esd_forms:
1: 'http://labornet.com/itc/ESD-1.pdf'
2: 'http://labornet.com/itc/ESD-2.pdf'
3: 'http://labornet.com/itc/ESD-3.pdf'
4: 'http://labornet.com/itc/ESD-4.pdf'
5: 'http://labornet.com/itc/ESD-5.pdf'
6: 'http://labornet.com/itc/ESD-6.pdf'
7: 'http://labornet.com/itc/ESD-7.pdf'
8: 'http://labornet.com/itc/ESD-8.pdf'
9: 'http://labornet.com/itc/ESD-9.pdf'
10: 'http://labornet.com/itc/ESD-10.pdf'
11: 'http://labornet.com/itc/ESD-11.pdf'
03: 'http://labornet.com/itc/OCIO-IT-03.pdf'
07: 'http://labornet.com/itc/OCIO-IT-07.pdf'
10: 'http://labornet.com/itc/OCIO-10.pdf'
13: 'http://labornet.com/itc/ESD-13.pdf'
14: 'http://labornet.com/itc/ESD-14.pdf'


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
2


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

Answer

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"]