代码之家  ›  专栏  ›  技术社区  ›  Int'l Man Of Coding Mystery

将哈希值传递给#新结果以值数组形式而不是正确的值

  •  -1
  • Int'l Man Of Coding Mystery  · 技术社区  · 6 年前

    在minitest中设置此设置,

     def test_id
        i = Item.new({
          :id          => 1,
          :name        => "Pencil",
          :description => "You can use it to write things",
          :unit_price  => BigDecimal.new(10.99,4),
          :created_at  => Time.now,
          :updated_at  => Time.now,
          :merchant_id => 2
                        })
        assert_equal 1, i.id  
    end
    

    出于某种原因,当创建时,调用 id 属性生成包含所有值的数组: [1,'Pencil','You can use it to write things',#<BigDecimal...>, 2018-07-24 14:43:36 -0600, 2018-07-24 14:43:36 -0600, 2]

    而不是整数 1 .

    在项目文件中,它看起来像您期望的那样

    require 'bigdecimal'
    require 'time'
    
        class Item
          attr_reader :id, :created_at, :merchant_id
          attr_accessor :name, :description, :unit_price, :updated_at
    
          def initialize(item_data)
            @id =           item_data[:id].to_i,
            @name =         item_data[:name],
            @description =  item_data[:description],
            @unit_price =   BigDecimal.new(item_data[:unit_price], 4),
            @created_at =   item_data[:created_at],
            @updated_at =   item_data[:updated_at],
            @merchant_id =  item_data[:merchant_id].to_i
          end
        end
    

    不太清楚这是怎么回事。

    投掷 pry 在断言和调用之前的测试方法中 i 结果

    #<Item:0x00007f8cc48eb4f0
     @created_at=2018-07-24 15:14:55 -0600,
     @description="You can use it to write things",
     @id=[1, "Pencil", "You can use it to write things", #<BigDecimal:7f8cc48eb4c8,'0.1099E2',18(27)>, 2018-07-24 15:14:55 -0600, 2018-07-24 15:14:55 -0600, 2],
     @merchant_id=2,
     @name="Pencil",
     @unit_price=#<BigDecimal:7f8cc48eb4c8,'0.1099E2',18(27)>,
     @updated_at=2018-07-24 15:14:55 -0600>
    

    在终点站。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Sergio Tulentsev    6 年前

    这是初始值设定项中的尾随逗号:

    def initialize(item_data)
      @id =           item_data[:id].to_i, # <=
      @name =         item_data[:name],    # <=
    

    他们所做的是让ruby看到这样的方法:

     @id = [item_data[id].to_i, @name = item_data[:name], ...]
    
        2
  •  1
  •   JesusTinoco    6 年前

    问题似乎是在每个设置变量的末尾添加逗号。检查此代码:

    require 'bigdecimal'
    require 'time'
    
    class Item
      attr_reader :id, :created_at, :merchant_id
      attr_accessor :name, :description, :unit_price, :updated_at
    
      def initialize(item_data)
        @id =           item_data[:id].to_i
        @name =         item_data[:name]
        @description =  item_data[:description]
        @unit_price =   BigDecimal.new(item_data[:unit_price], 4)
        @created_at =   item_data[:created_at]
        @updated_at =   item_data[:updated_at]
        @merchant_id =  item_data[:merchant_id].to_i
      end
    end