Hi,
I need to open files, just the first 75 bytes of them, and determine if
there’s a string in the data. If the string is there, then, I do
something. If not, then I do something else.
Here’s my IRB try. I don’t understand why it’s coming back to me with a
positive, meaning, it seems to see the string, when, the string
definitely isn’t in the file.
Alle giovedì 3 gennaio 2008, Peter B. ha scritto:
Peter
irb(main):006:1> end
mathtype file.
=> nil
irb(main):007:0>
Because String#scan always returns an array, which is empty if there
were no
match, but which is always true. You should replace
if stuff.to_s.scan(…) then
with
unless stuff.to_s.scan(…).empty? then
If you only want to check whether stuff contains that substring, I think
you
should use String#match, not String#scan. String#match returns an object
of
class MatchData if there’s a match and nil otherwise, which allows you
to use
the conditional like you did your code (check the ri documentation for
String#scan and String#match for more details).
By the way, why do you call to_s on the result of File.open ? Isn’t it
already
a string?
If you only want to check whether stuff contains that substring, I think
you
should use String#match, not String#scan. String#match returns an object
of
class MatchData if there’s a match and nil otherwise, which allows you
to use
the conditional like you did your code (check the ri documentation for
String#scan and String#match for more details).
By the way, why do you call to_s on the result of File.open ? Isn’t it
already
a string?
I hope this helps
Stefano
Yup. This helps a lot. I used .match and it worked beautifully.
Regarding the .to_s thing, that’s just me being neurotic and thinking I
needed it. No, I don’t need it.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.