Alexis Knox
Alexis Knox

Reputation: 37

no overload matches 'Array(Person)#+' with type Person

So I just started learning Crystal because I like both Ruby and C, but I just can't get the hang of the syntax yet. I think I am close, but I'm stuck with this error.
no overload matches 'Array(Person)#+' with type Person Overloads are: - Array(T)#+(other : Array(U)) people += Person.new("Person#{id}")

Here is the code.

class Person
    def initialize(name : String)
        @name = name
        @age = 0
    end

    def name
        @name
    end

    def age
        @age
    end
end

people = [] of Person
counter = 0
id = 0

loop do
    id+=1
    people += Person.new("Person#{id}")

    counter+=1
    break if counter = 5
end

puts(people)

What am I doing wrong? Thanks in advance!

Upvotes: 2

Views: 331

Answers (2)

Jens Nedregård
Jens Nedregård

Reputation: 199

I see your answer was answered, but because of crystals awesomeness i think it is worth mentioning that all your provided code can also be written as:

class Person
  getter name, age = 0
  def initialize(@name : String); end
end

puts Array.new(5) { |i| Person.new("Person#{i + 1}") }

Awesome right? :D

The getter is a macro defined in the Object class, which is a superclass of every class.

And

 def initialize(@name)
 end

Is just the same as writing

 def initialize(name)
   @name = name
 end

And there's this neat little line:

Array.new(5) { |i| Person.new("Person#{i + 1}") }

Array.new(5) creates an empty array, and yields every integer from and including 0, up to and not including 5. Therefore, the previously empty arrays index of the number passed, is assigned to the value returned by the block. So we create a person with the index plus 1 in the block, and since the last value in the block becomes the return value, unless return is used, the array index of i's value becomes the new person.


Whether to write

def initialize(@name); end

Or

def initialize(@name)
end

Is just your personal preferences

Upvotes: 4

WPeN2Ic850EU
WPeN2Ic850EU

Reputation: 995

You're trying to put together an Array and a Person. But you can add Array to Array only.

To solve it, you should use Array#<<, like this: people << Person.new("Person#{id}")

NOTE: Check your line 25, it should be break if counter == 5

Upvotes: 5

Related Questions