FamousSnake
FamousSnake

Reputation: 451

Ruby syntax error when initiating an array of objects with no parentheses

I got this error:

SyntaxError ((irb):8: syntax error, unexpected tSTRING_BEG, expecting ']')

Person.new "Nick",

(irb):8: syntax error, unexpected ',', expecting end-of-input

Person.new "Nick",

When executing the following code:

class Person
    def initialize(name)
        @name = name
    end
end

a = [
    Person.new "Nick",
    Person.new "James"
]

I understand how I can fix it, I just wanna know why exactly it happens.

Upvotes: 0

Views: 566

Answers (3)

mehrnoush
mehrnoush

Reputation: 21

if you run a = ["hello" "there", "some" "where"] it will return => ["hellothere", "somewhere"]

maybe that happens because it tries to attach string to class!

Upvotes: 0

matthewd
matthewd

Reputation: 4420

The question is:

I understand how I can fix it, I just wanna know why exactly it happens


Without the parentheses it is ambiguous: it could equally mean

  • [Person.new("Nick"), Person.new("James")], or
  • [Person.new("Nick", Person.new("James"))]

Upvotes: 1

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

I think it is because ruby is confused in interpreting spaces between Person.new and its argument(s). Use parenthesis () around name:

a = [
  Person.new("Nick"),
  Person.new("James")
]

Upvotes: 3

Related Questions