The story of an array that I personally became "Python, was that so?" While touching Python recently. (By the way, I have a past that I stumbled upon and melted for an hour or two)
The following are different ways to write when trying to add a string to an array.
arr = []
arr += "hello" # => ['h', 'e', 'l', 'l', 'o']
arr.append("hello") # => ['hello']
Since + =
is an array concatenation and receives an iterable object as an operand, the character string is treated as an array of characters and stored character by character in the array.
For example, if you pass an int type, of course this is not iterable and you will get an error.
I haven't examined it in detail, but when I check it with irb, Ruby seems to be similar.
arr = []
arr += 'hello' # => TypeError: no implicit conversion of String into Array
arr.append("hello") # => ['hello']
However, in the case of Ruby, if it is + =
, it will be Type Error: no implicit conversion of String into Array
, and you will notice with an error that the behavior is not as intended.
That's right, if you ask me, but I wrote it as a commandment because if I inadvertently added an array element in Python code with a fairly complicated implementation, it could take time to investigate.
Recommended Posts