From: Greg Millam Date: 2002-12-19T17:41:46+09:00 Subject: Re: Few question about IO On Thu, 19 Dec 2002, Radek Hnilica wrote: > Hello, > > I have few questions to wise mans. > > First is about IO. I want read from input stream words or longs in given endianity. How can I extend IO class to have a method to read word or long word > from stream. I try > > class IO > def getw > getc()+256*getc() > end > public :getw > end > > but calling: > puts ARGF.getw() > > gives me > ./dis68k.rb:45: private method `getw' called for # (NoMethodError) > $ ruby -e 'puts ARGF.class' Object -- foo.rb: def Object def getw getc + 256*getc end end $ruby -r foo -e 'puts ARGF.getw' < hi 26984 > > Next question is about Regular expression. I have a Hash filled with > keyword, label pairs. Some of the keywords contains characters like: > + & ( and other strange characters. Then I have a string in which I > want replace all ocurrences of keywords with string linkend="#{label}"/> the keyword must be like a word separated from > other text by white spaces. Now I use this method > > def mangle(s, dict) > dict.each_pair do |key,id| > word = Regexp.quote(key) > s.gsub!(%r[ #{word} ], %Q[ ]) > s.gsub!(%r[^#{word} ], %Q[ ]) > s.gsub!(%r[ #{word}$], %Q[ ]) > end > s > end > > Is there any better and speedy way how to do it. I'm not great ruby hacker. > The > s.gsub!(%r[\b#{word}\b], %Q[ ]) > > does not work because word can be + , : , ; , ... . In my case word > is any sequence of printable characters separated from others with > white spaces. > > The main goal is replace all ocurences of given words with to > that word. The table with words and its linkends is in file. The > word is any sequence of printable characters separated from others by > whitespaces. \s is all white space characters, and \S is all non-whitespace characters. since you also wish to match end of line, this might work: s.gsub(%r[(\s|^)#{word}(\s|$)],%Q[\1#{id}\2]) This has one flaw: s = "foo foo foo foo" word = "foo" id = "bar" s.gsub(%r[(\s|^)#{word}(\s|$)],%Q[\1#{id}\2]) gets: bar foo bar foo because the space after the first foo (bar) is ignored when looking for the first space of the next word. One possible solution may be to do it twice. Any others escape me > -- > Radek Hnilica -- Greg Millam walker at deafcode.com