【问题标题】:Ruby Array AttributesRuby 数组属性
【发布时间】:2016-07-18 15:53:19
【问题描述】:

我正在尝试使用 shopify-api gem 访问 Shopify API。特别是,我正在尝试访问包含在数组中的商品的价格。

product = ShopifyAPI::Product.find(id)
variant = product.variants

variant 这里是一个数组,当我做puts variant.inspect 时,我得到了

[
  #<ShopifyAPI::Variant:0x000000041c9e50 @attributes={
    "id"=>23923477191,
    "title"=>"Default Title",
    "price"=>"6.00",
    "sku"=>"shirts",
    "position"=>1,
    "grams"=>0,
    "inventory_policy"=>"deny",
    "compare_at_price"=>nil,
    "fulfillment_service"=>"manual",
    "inventory_management"=>"shopify",
    "option1"=>"Default Title",
    "option2"=>nil,
    "option3"=>nil,
    "created_at"=>"2016-06-30T14:06:07-04:00",
    "updated_at"=>"2016-07-16T19:00:07-04:00",
    "taxable"=>true,
    "barcode"=>"",
    "image_id"=>nil,
    "inventory_quantity"=>1,
    "weight"=>0.0,
    "weight_unit"=>"kg",
    "old_inventory_quantity"=>1,
    "requires_shipping"=>true
  }, @prefix_options={:product_id=>7509869767}, @persisted=true>
]

如何访问/更改“@attributes”下的“价格”?

【问题讨论】:

    标签: ruby shopify


    【解决方案1】:

    属性是 Ruby 所说的对象属性。只需像访问大多数其他语言的属性一样访问它。

    获取你想要的数组的item(本例中为0),然后访问price属性

    variant[0].price

    【讨论】:

      【解决方案2】:

      用途:

      variant.first["price"]

      variant 数组有 3 个元素; @attributes 元素是第一个。 这个@attributes 元素是一个哈希映射,您正在查找键"price" 处的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-30
        • 2022-01-01
        • 2013-05-01
        相关资源
        最近更新 更多