cresjoy cresjoy - 3 months ago 7x
Ruby Question

Class inheritance in Ruby

Why are numbers being returned as an array?

class Employee
def initialize(n,i,ph,ad)
@number = n, @id = i , @phone = ph, @adress =ad
class Getemploy < Employee
def get_data
return "The employee number is : #{@number} with id : #{@id} with phone #{@phone} with adress: #{@adress}"

# => The employee number is : ["1", "2", "3", "4"] with id : 2 with phone 3 with adress: 4


The behaviour is introduced by assignment expressions, not inheritance. When you type:

@number = n, @id = i , @phone = ph, @adress =ad

What really means is

  • Assign ad to @address
  • Assign ph to @phone
  • Assign i to @id
  • Assign [n, the result of assigning i to id, which is i, the result of assigning ph to phone, which is ph, the result of assigning ad to address, which is ad] to number, which is a list.

So, the fix that problem, you will need to assign the properties individually, like so.

@number = n
@id = i 
@phone = ph
@adress = ad

Edit: you can also be smart and do a destructured assignment, like so...

@number , @id , @phone , @adress = [n, i, ph, ad]