Ruby Array Attributes - ruby

I am trying to access the Shopify API using the shopify-api gem. In particular, I am trying to access the price of an item, which is contained in an array.
product = ShopifyAPI::Product.find(id)
variant = product.variants
variant here is an array, and when I do puts variant.inspect, I get
[
#<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>
]
How do I access/change 'price' under '#attributes`?

Attributes are what Ruby calls object properties. Just access it as you would a property in most other languages.
Get the item of the array you want (0 in this example) and then access the price attribute
variant[0].price

Use:
variant.first["price"]
The variant array has 3 elements; the #attributes element is the first.
This #attributes element is a hash map, and you are looking for the value at key "price".

Related

How can i sort an arrays of hashes in ruby

this is the code i tried to sort it by name,email,country,comments.first i tried sorting by names
array_of_hashes=[
{"Name"=>"Akash","Email"=>"akash85#gmail.com","Country"=>"India",'Comments'=>"9898984523"},
{"Email"=>"rahul#hotmail.com","Country"=>"Srilanka","Name"=>"Rahul"},
{"Country"=>"India", "Comments"=>"3455358782","Email"=>"veera#gmail.com","Name"=>"Veera"},
{"Name"=>"Akash","Country"=>"India", "Email"=>"akash37#yahoo.com", "Comments"=>"8898788932"}
]
puts array_of_hashes.sort_by { |element| element.keys(&:Name)}
but the displayed output is not as i expected,it prints the same which i mentioned above.
i expected to code the final output should be like this
Name Email Country Comments
Akash akash37#live.com India 8898788932
Akash akash85#gmail.com India 9898984523
Rahul rahul#hotmail.com Srilanka
Veera veera#gmail.com India 3455358782
Help me to resolve these.Thanks in advance!
You should look at what element.keys(&:Name) evaluates to in the block that you're passing to #sort_by. All methods in Ruby can be given a block, you can pass it even if the method doesn't use it. Hash#keys doesn't use the block so element.keys(&:Name) is the same as element.keys and you end up trying to sort by the array ['Name', 'Email', 'Country', 'Comments'].
If you want to sort by the name, say so:
hash.sort_by { |element| element['Name'] }
Keep in mind that your keys are strings so you want element['Name'] rather than element[:Name]. I'd also recommend that you don't call your array of hashes hash, that's a little confusing.
not_a_hash = [
{"Name"=>"Akash","Email"=>"akash85#gmail.com","Country"=>"India",'Comments'=>"9898984523"},
{"Email"=>"rahul#hotmail.com","Country"=>"Srilanka","Name"=>"Rahul"},
{"Country"=>"India", "Comments"=>"3455358782","Email"=>"veera#gmail.com","Name"=>"Veera"},
{"Name"=>"Akash","Country"=>"India", "Email"=>"akash37#yahoo.com", "Comments"=>"8898788932"}
]
sorted_values = not_a_hash.map{|h| h.values_at("Name", "Email", "Country", "Comments")}.sort

Pulling out values from element of array

I have a hash that is generated by IB-ruby and looks like this:
{:contract=>#<IB::Stock:0x0000560721a1aee0 #attributes={:symbol=>"AAPL", :currency=>"USD", :sec_type=>"STK", :created_at=>2019-10-23 23:03:35 +0200, :con_id=>0, :right=>"", :include_expired=>false, :exchange=>"SMART"}>, :last_price=>0.24308e3, :high=>0.24324e3, :low=>0.24122e3, :close_price=>0.23996e3, :open_tick=>0.2421e3, :bid_price=>0.2431e3, :ask_price=>0.24319e3}
How do I pull out the symbol ("AAPL") and the closing_price (0.23996e3) for further processing?
What you posted is the string representation of a Hash.
This Hash has a key :close_price, whose value you can access in this way:
your_hash[:close_price] #=> 0.23996e3
The hash also has a key :contract whose value is an instance of the class IB::Stock. To access this object:
ib_stock_instance = your_hash[:contract]
ib_stock_instance.class #=> IB::Stock

Accessing specific attribute of an object

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.
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'] }
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"]
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']

How do I extract a value from this Ruby hash?

I'm using the Foursquare API, and I want to extract the "id" value from this hash
[{"id"=>"4fe89779e4b09fd3748d3c5a", "name"=>"Hitcrowd", "contact"=>{"phone"=>"8662012805", "formattedPhone"=>"(866) 201-2805", "twitter"=>"hitcrowd"}, "location"=>{"address"=>"1275 Glenlivet Drive", "crossStreet"=>"Route 100", "lat"=>40.59089895083072, "lng"=>-75.6291255071468, "postalCode"=>"18106", "city"=>"Allentown", "state"=>"Pa", "country"=>"United States", "cc"=>"US"}, "categories"=>[{"id"=>"4bf58dd8d48988d125941735", "name"=>"Tech Startup", "pluralName"=>"Tech Startups", "shortName"=>"Tech Startup", "icon"=>"https://foursquare.com/img/categories/shops/technology.png", "parents"=>["Professional & Other Places", "Offices"], "primary"=>true}], "verified"=>true, "stats"=>{"checkinsCount"=>86, "usersCount"=>4, "tipCount"=>0}, "url"=>"http://www.hitcrowd.com", "likes"=>{"count"=>0, "groups"=>[]}, "beenHere"=>{"count"=>0}, "storeId"=>""}]
When I try to extract it by using ['id'], I get this error can't convert Symbol into Integer. How do I extract the value using ruby? Also, how do I do this for multiple hashes extracting the "id" value each time?
Please pardon my inexperience. Thanks!
It's wrapped in an array, that's what the [ and ] mean on the start and end. But it also looks like this array only one object in it, which is the hash you really want.
So assuming you want the first object in this array:
mydata[0]['id'] # or mydata.first['id'] as Factor Mystic suggests
But usually when an API returns an Array there is a reason (it might return many results instead of just one), and naively plucking the first item from it my not be what you want. So be sure you are getting the kind of data you really expect before hard coding this into your application.
For multiple hashes, if you want to do something with the id (run a procedure of some kind) then
resultsArray.each do |person|
id = person["id"] #then do something with the id
end
If you want to just get an array containing the ids then
resultsArray.map{|person| person["id"]}
# ["4fe89779e4b09fd3748d3c5a", "5df890079e4b09fd3748d3c5a"]
To just grab the one item from the array, see Alex Wayne's answer
To get an array of ids, try: resultsArray.map { |result| result["id"] }

does ruby have an elegant way to say array2 = some_lookup_method(array1)

I have an array short_code[] that contains an array of short product identifiers such as ["11111", "2222", "33333"]
I want to create a copy of the array that contains the corresponding 'long code' data:
long_code[i] = my_lookup_long_code(short_code[i])
While simple iteration is easy, I'm wondering, as a relative ruby newbie, what is the 'ruby way' to create an array which is a simply method() applied on every element in the original array?
You can use the map command, which will return a new array with the results of your code block:
long_code = short_code.map{ |code| my_lookup_long_code(code) }

Resources