Having trouble appending a string to an array using push!


#1

Hello guys,
I am struggling with how to get push! to add my nextpitch variable to my pitcharray array. I get this error message: ERROR: MethodError: no method matching push!(::String, ::String)

Thanks,
Nakul

pitch0 = 200
    pitcharray = "d pitch1 $pitch0;"
    pitchn = 5
    pitchn = 1:pitchn
    multiplier = 4
    for n = 1:size(pitchn,1)
        nextpitch = "d pitch$n $(pitch0*multiplier*pitchn[n])"
        push!(pitcharray,nextpitch)
    end

#2

I have troubles understanding what you are trying to do but pitcharray is not an array; it’s a string.

You can do something like pitcharray = ["d pitch1 $pitch0"] but as I said, don’t know what you want to do :wink:

If you want to convert the array to a string again, you can do it for example like this:

final_pitch = foldr(*, pitcharray)
println(final_pitch)

Alternatively (just noticed you are using the ; as a delimiter):

final_pitch = join(pitcharray, ';')
println(final_pitch)

#3

I think you might want to do something like this, but I’m not 100% sure what you are trying to accomplish

pitcharray *= "d pitch$n $(pitch0*multiplier*pitchn[n])"

String can be concatenated with the * operator, it’s not an Array by the way.


#4

If it’s an array of strings you want, I’d recommend something like this:

[n => "d pitch$n $(pitch0*multiplier*n)" for n = 1:5]

#5

Thank you guys. I like all the methods. My understanding is that @bennedich’s solution is the most compact. @chakravala’s solution keeps everything as a string instead of an array. @tamasgal’s solution was the easiest for me to implement because it just involved me bracketing the pitcharray to make it into an array (I had thought a string is automatically an array, but I guess it’s of type string)! I also like the foldr function, I’d never heard of it!

Thanks for the help!