beginner's q about eval and/or code blocks

J

Jeff Myers

This ruby program successfully prints all 5-letter words starting with
'j'
(in a text file containing all current U.S. English Scrabble words).

fp = File.open('C:\Documents and Settings\User\twl06FromMac.txt')
fp.each do |line|
puts line if line =~ /^j....$/
end

I would like to allow the user to enter the regex rather than have it
hard-coded as above. I've tried to get eval to work after building a
string to pass it. No luck so far.

I'm positive this is easy in Ruby but currently it's driving me nuts.
 
J

Jeff Myers

Brian said:
Try something like:

str = $stdin.gets.chomp
re = Regexp.new(str)
...
puts line if line =~ re

Excellent! Thanks. Now I'll spend some time digging into the Why of
it all. Apparently the match operator needs one side to be a
regular expression object.
 
J

Jeff Myers

Brian said:
Try something like:

str = $stdin.gets.chomp
re = Regexp.new(str)
...
puts line if line =~ re

If I put the user input into a simple loop, it has trouble:
"private method 'chomp' called for nil:NilClass (NoMethodError).
Is there a problem with redefining re?
 
B

Brian Candler

Jeff said:
If I put the user input into a simple loop, it has trouble:
"private method 'chomp' called for nil:NilClass (NoMethodError).
Is there a problem with redefining re?

No. It's because you're trying to do nil.chomp. Possibly, $stdin.gets is
returning nil for end-of-file. You need to post your actual code if you
want an accurate answer, otherwise I have to guess.

(The "private method" error is confusing; just pretend it said "no such
method". It's because there's also a standalone 'chomp' method defined
in the Kernel module. This is a legacy Perlism, and serves little
purpose except to confuse newcomers :)

Better to test for nil before you chomp. Example:

loop do
print "Enter a pattern: "
line = $stdin.gets
break if line.nil?
line.chomp!
re = Regexp.new(line)
.. rest of logic goes here
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top