简体   繁体   中英

Dictionary to string

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.

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.

You can do it with keysAndValuesDo too. Just remember that a Dictionary isn't ordered, and there is no nice keysAndValuesDo:separatedBy:

|dict first str|
dict := OrderedIdentityDictionary 
    newFromPairs:#(#DOB Date #Name String #Salary Number).
first := true.
str := String streamContents: [  :s |
    dict keysAndValuesDo: [ :key :value |
        first ifFalse: [ s nextPutAll: ',' ]
            ifTrue: [ first := false].
        s   nextPutAll: key; space;
            nextPutAll: '';
            nextPutAll: value] ].
str

'DOB Date,Name String,Salary Number'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM