skip to Main Content

Hello I have the following object

object =  [#<ShopifyAPI::DiscountCode:0x000000000e1c78a8 @attributes={"code"=>"Disc2", "amount"=>"1.00", "type"=>"percentage"}, @prefix_options={}, @persisted=true>]

How can I properly access the “code” name of that object?

I have tried object[:code] and object.code but it appears I am overlooking something.

3

Answers


  1. First, object is array:

    obj0 = object[0]
    

    Second, this is instance variable:

    attributes = obj0.instance_variable_get(:@attributes)
    

    Last, gets values by keys:

    attributes['code']
    
    Login or Signup to reply.
  2. object is an array of ShopifyAPI::DiscountCode.
    The best way to access it is

    object[0].attributes['code']
    

    If u want code of all the objects available in the array, you could get the array of values by

    object.map { |obj| obj.attributes['code'] }
    
    Login or Signup to reply.
  3. Given that this is an Array of ShopifyAPI::DiscountCodes (which inherit from ActiveResource::Base)

    You can call the code method on them. eg:

    object[0].code 
    #=> "Disc2"
    object.map(&:code) 
    #=> ["Disc2"]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search