Date #Name->String #Salary->Number )". I need to create a string that should be s...">

Dictionary for string

I have a dictionary "a Dictionary(#DOB->Date #Name->String #Salary->Number )". I need to create a string that should be str:= "DOB Date,Name String,Salary Number". I tried to use keysAndValuesDo: but could not concatenate them correctly.

+4
source share
2 answers

You can do it in a beautiful way:

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

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

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

note that if you want to delegate printing to the object itself and not convert it to a string and manually enter it into the stream, you can use:

aStream
  print: assoc key;
  ....

#print: #printOn: . #printOn: - defat, , . #asString #printOn: .

+4

AndValuesDo . , , AndValuesDo: separateBy:

|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'
+1

Source: https://habr.com/ru/post/1548434/


All Articles