[Note: parts of this message were removed to make it a legal post.]
On Fri, Jan 29, 2010 at 6:50 PM, joemac <> wrote:
> Hi All,
>
> I dont know how to use a variable in a regex searchstring.
> ruby seems to only handle hardcoded serachstring in
> regex's. How do you do this. My code is below.
>
> Also - how do you put a variable name in a
> File.open("filename.txt") statement like this:
> File.open(filevariable) where filevariable can
> be set to anything? I could not find this in
> the docs.
>
> Thanks, --Joe
> ================ snip code ===============
> #!/usr/bin/ruby
>
> F = "filename.txt"
> searchstring = ARGV[0]
>
> print "searchstring is ", searchstring, "\n"
>
>
> File.open("filename.txt").each { |line|
> # this fails puts line if line =~ searchstring
> # this fails puts line if line =~ /searchstring/
> # this fails puts line if line =~ "searchstring"
>
> #this works
> # puts line
> }
>
>
This should work, here is an image showing how to use it:
http://tinypic.com/r/b5pi7m/6
filename = 'source.txt'
to_find = Regexp.new ARGV[0]
puts "The Regexp is: #{to_find.inspect}"
File.open(filename).each do |line|
if line =~ to_find
puts "This line matches: #{line}"
puts "This is what matches: #{line[to_find]}"
end
end