2016-06-29 43 views
-3

数値が配列として返されるのはなぜですか?Rubyのクラス継承

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

puts Getemploy.new("1","2","3","4").get_data 
# => The employee number is : ["1", "2", "3", "4"] with id : 2 with phone 3 with adress: 4 

答えて

4

この動作は、継承ではなく、代入式によって導入されています。あなたが入力すると:

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

を本当に意味は何割り当て

  • @addressph
  • @phoneに割り当て i割り当て[ n、割り当ての結果
  • @idに割り当てる ad

    • ですi〜リストであるnumberからiある、adあるphあるphonephを割り当てる結果、addressadを割り当てる結果、]。

    したがって、この問題を修正するには、プロパティを個別に割り当てる必要があります。

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

    編集:あなたは、スマートすることができ、そのような...

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

    ありがとう!助けてくれた –

    3

    destructured assignmentは、なぜ数は配列として返されているのですか?

    Employee#initializeメソッドでは、複数の値を@numberに割り当てます。 Rubyが複数の値を表す方法は、Arrayです。

    IOW:

    foo = 1, 2, 3 
    # => [1, 2, 3]