[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Does Ruby have anything like isprint?

mkcon

12/2/2004 6:13:00 AM

Hi!

I want to print out the 'printable' characters from a binary
data stream.
Is there anything like C's isprint() function in Ruby?

Thanks,
Martin.

3 Answers

Dave Burt

12/2/2004 7:45:00 AM

0

"Martin Kahlert" <mkcon@gmx.de> wrote...
> Hi!
>
> I want to print out the 'printable' characters from a binary
> data stream.
> Is there anything like C's isprint() function in Ruby?
>
> Thanks,
> Martin.

You can use the POSIX regular expression 'metacharacter' [:print:] to match
a printing character.

def isprint(c)
/[[:print:]]/ === c.chr
end

Or you can .gsub(/[^[:print:]]/, '') on a string, etc.


Mark Hubbart

12/2/2004 7:57:00 AM

0

Hi,

On Thu, 2 Dec 2004 15:17:43 +0900, Martin Kahlert <mkcon@gmx.de> wrote:
> Hi!
>
> I want to print out the 'printable' characters from a binary
> data stream.
> Is there anything like C's isprint() function in Ruby?

Not that I know of. But here's a way to get a copy of a string with
all non-printable characters stripped out:

# get a string with all possible byte values:
str = (0..255).map{|b| b.chr}.join
# print all printable characters:
print str.gsub(/[[:^print:]]+/, "")

That gsub there finds all runs of non-printing characters, and
replaces them with an empty string (ie, nothing).

HTH,
Mark


Robert Klemme

12/2/2004 10:48:00 AM

0


"Dave Burt" <dave@burt.id.au> schrieb im Newsbeitrag
news:LJzrd.55898$K7.47722@news-server.bigpond.net.au...
> "Martin Kahlert" <mkcon@gmx.de> wrote...
> > Hi!
> >
> > I want to print out the 'printable' characters from a binary
> > data stream.
> > Is there anything like C's isprint() function in Ruby?
> >
> > Thanks,
> > Martin.
>
> You can use the POSIX regular expression 'metacharacter' [:print:] to
match
> a printing character.
>
> def isprint(c)
> /[[:print:]]/ === c.chr
> end
>
> Or you can .gsub(/[^[:print:]]/, '') on a string, etc.

I prefer to use scan as this is likely more memory efficient (no copy of
the whole thing needed):

binary_string.scan(/[[:print:]]+/) { |s| print s }

Kind regards

robert