Make a stream from a string, for reading

From Cuis CookBook
Jump to navigation Jump to search

One of the things that gets most in your way when you start with Smalltalk is that if often requires you to work with aStream when you would think you could just pass in aString.

Problem. I need to convert a string containing an hex number into a decimal one. I found Integer Class>>readFrom: but damn, it requires aStream as input.

Solution. Follow the recipe below, it is not difficult when you know how to make a String be a Stream, that is using ReadStream Class>>on: aString.

s1 _ 'D79BC6684BB6214D4D01' .

Integer readFrom: (ReadStream on: s1) base: 16.   "=> 1018182335908661403929857 "

Or just use String>>readStream method:

Integer readFrom: 'D79BC6684BB6214D4D01' readStream base: 16.   "=> 1018182335908661403929857 "

Mariano Montone last updated this on 23-11-2021. Example tested in Cuis-5.0-4973.image.