Dictionary to string

pharo, smalltalk

Solution

You can do it in a nice way like this:

(dict associations collect: [ :assoc |
  assoc key asString, ' ', assoc value asString ])
    joinUsing: $,

if you want to use #do: and streams, you can go this way:

dict associations
  do: [ :assoc |
    aStream
      nextPutAll: assoc key asString;
      space;
      nextPutAll: assoc value asString ]
  separatedBy: [ aStream nextPut: $, ]

please note that in case you want to delegate printing to the object itself and not convert it to string and put in on the stream manually, you can use:

aStream
  print: assoc key;
  ....

`#print:` method of a stream sends `#printOn:` to the parameter. `#printOn:` is the defat method you have to override to make your object properly printable on a stream. `#asString` uses `#printOn:` for a lot of objects.

Problem

I have dictionary `"a Dictionary(#DOB->Date #Name->String #Salary->Number )"`. I need to create a string which should be `str:= "DOB Date,Name String,Salary Number"` . I tried using `keysAndValuesDo`: but couldn't concatenate them correctly.

Original source