'why does code replace element in json array, rather than adding new element

This code reads in a json file, attempts to add a new line within the json structure, writes it back to the same file:

require 'json'

filepath="/tmp/my/my-apply-iam-role.assume-role.json"
user="harold"
file=File.read(filepath)

data=JSON.parse(file)

lastLine=data["Role"]["AssumeRolePolicyDocument"]["Statement"][0]["Principal"]["AWS"][-1]

# example: lastLine = "arn:aws:iam::123123123123:user/username.lastname"
marker=lastLine.split(":")[-1]
# this line *replaces* the last line in the json "AWS" array
# instead, I'd like to just be manipulating a string here.
lastLine[marker]="user/#{user}"

puts "New string: "
puts lastLine
puts "Existing block: "
puts JSON.dump(data)

# this line adds the new string back to the JSON structure
data["Role"]["AssumeRolePolicyDocument"]["Statement"][0]["Principal"]["AWS"] += [lastLine]

File.write(filepath, JSON.dump(data))

The result of this execution is 1.) replace the last line in the "AWS" array with a 'harold', 2.) add a new 'harold' line again.

How do I manipulate a plain old string in the middle of the file, rather than the entire JSON structure?



Solution 1:[1]

aCopy = String.new(data["Role"]). 

These are different objects => aCopy.equal?(data["Role"]) is false. And here's a SO thread

yep that was it - thanks @radarbob – Jason Michael 1 hour ago

comment transposed as answer. (points are not pointless)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 radarbob