Reputation: 460
Okay, so I'm building something that takes a text file and breaks it up into multiple sections that are further divided into entries, and then puts <a>
tags around part of each entry. I have an instance variable, @section_name
, that I need to use in making the link. The problem is, @section_name
seems to lose its value if I look at it wrong. Some code:
def find_entries
@sections.each do |section|
@entries = section.to_s.shatter(/(some) RegEx/)
@section_name = $1.to_s
puts @section_name
add_links
end
end
def add_links
puts "looking for #{@section_name} in #{@section_hash}"
section_link = @section_hash.fetch(@section_name)
end
If I comment out the call to add_links
, it spits out the names of all the sections, but if I include it, I just get:
looking for in {"contents" => "of", "the" => "hash"}
Any help is much appreciated!
Upvotes: 1
Views: 70
Reputation: 118261
$1
is a global variable which can be used in later code.$n
contains the n-th (...)
capture of the last match
"foobar".sub(/foo(.*)/, '\1\1')
puts "The matching word was #{$1}" #=> The matching word was bar
"123 456 789" =~ /(\d\d)(\d)/
p [$1, $2] #=> ["12", "3"]
So I think @entries = section.to_s.shatter(/(some) RegEx/)
line is not doing match properly. thus your first matched group contains nothing. so $1
prints nil.
Upvotes: 1