[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: turning a string into array of ASCII bytes

Peter

11/26/2003 1:45:00 PM

2 Answers

Simon Strandgaard

11/26/2003 2:00:00 PM

0

On Wed, 26 Nov 2003 22:44:37 +0900, Peter wrote:

>> What is the shortest, most straightforward way (without temporary
>> variables, etc)?
>>
>> My best route is now "1234".split(//).collect{|c|c[0]} but I'm sure
>> there is a much better way. Also it's a bit slow.
>
> irb(main):003:0> "1234".unpack("c*")
> => [49, 50, 51, 52]



Another possible solution could be (if you use Ruby-1.8.1):

server> ruby a.rb
["78", "79", "7a"]
server> cat a.rb
require 'enumerator'
str = "xyz"
enum = Enumerable::Enumerator.new(str, :each_byte)
p enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]
server>

--
Simon Strandgaard

David Garamond

11/26/2003 2:04:00 PM

0

Peter wrote:
>>What is the shortest, most straightforward way (without temporary
>>variables, etc)?
>>
>>My best route is now "1234".split(//).collect{|c|c[0]} but I'm sure
>>there is a much better way. Also it's a bit slow.
>
>
> irb(main):003:0> "1234".unpack("c*")
> => [49, 50, 51, 52]
>
> Is that what you want?

Of course. I forgot all about pack/unpack.

Thanks!
--
dave