Does Ruby have anything like isprint?

M

Martin Kahlert

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.
 
D

Dave Burt

Martin Kahlert said:
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.
 
M

Mark Hubbart

Hi,

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
 
R

Robert Klemme

Dave Burt said:
Martin Kahlert said:
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
 

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,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top