Is there a Hash nil check for fetch? - ruby

I'm using the facebook graph-api and I'm fetching the checkin keys. Most places have this checkin key, but every once in a while I find a place with no checkins that does not have this key. Is there a way to check for nil and prevent the following code from blowing up my very large rake?
graph.get_object(5811874893).fetch("checkins")
KeyError: key not found: "checkins"
x = graph.get_object(x.place_id)["checkins"]
Based on feedback below I have the following error, with the same theme: nil checking. How would you handle this?
nil can't be coerced into Fixnum

Have you tried seeing if has_key? is available, or using graph.get_object(5811874893)["checkins"] rather than graph.get_object(5811874893).fetch("checkins")?
To return 0 if there isn't checkins, do
graph.get_object(5811874893).fetch("checkins") { 0 }
The block after fetch specifies what to do if "checkins" doesn't exist.

Why don't you just do
graph.get_object(5811874893)["checkins"]
If you access a hash using [], no error will be raised, and you'll get a nil value (as long as the hash doesn't set it to something else).

What you want is this:
graph.get_object(5811874893).fetch("checkins", 0)
fetch accepts a second optional param which represents the default value.

Related

Access value from a Netsuite hash, Enumerator

Hi I am trying to extract a value from a Netsuite hash inside custom fields, and some others, which typically look like this - `
"custbody_delivery_ticket_number"=>
{
"script_id"=>"custbody_delivery_ticket_number",
"internal_id"=>"2701",
"type"=>"platformCore:DateCustomFieldRef",
"attributes"=> {
"value"=>"123abc"
}
}` and want the value of it inside of attributes.
Have tried many different ways, but one in particular -
delivery_ticket_number: "#{netsuite_sales_orders.custom_field_list.custom_fields.select['custbody_nef_meter_ticket_number']['attributes']['value']}",
throws error for class Enumerator, NoMethodError: undefined method `[]' for #Enumerator:0x00005589ec778730 which indicates may be getting close, but doing something wrong.
If anyone has any idea how to get values from these kind of hashes?
(Am told by the system admin that it is the correct custbody identifier)
Many Thanks
Eventually fixed this, grabbing Netsuite custom fields with a select of script_id by name,and map as below:
delivery_date:netsuite_sales_order.custom_fields_list.custom_fields.select { |field| field.script_id == 'custbody_delivery_date' }.map { |field| field.value }.first
First selecting the script_id by unique name, then mapping to the value. Was able to get any custom field like this, preferable as they can move and might not have the same index if use an index to grab them, fetching an incorrect value. This way ensures getting the correct data even if the item is moved up or down in the custom fields list.
Thanks for everyones help!

Create an object if one is not found

How do I create an object if one is not found? This is the query I was running:
#event_object = #event_entry.event_objects.find_all_by_plantype('dog')
and I was trying this:
#event_object = EventObject.new unless #event_entry.event_objects.find_all_by_plantype('dog')
but that does not seem to work. I know I'm missing something very simple like normal :( Thanks for any help!!! :)
find_all style methods return an array of matching records. That is an empty array if no matching records are found. And an empty is truthy. Which means:
arr = []
if arr
puts 'arr is considered turthy!' # this line will execute
end
Also, the dynamic finder methods (like find_by_whatever) are officially depreacted So you shouldn't be using them.
You probably want something more like:
#event_object = #event_entry.event_objects.where(plantype: 'dog').first || EventObject.new
But you can also configure the event object better, since you obviously want it to belong to #event_entry.
#event_object = #event_entry.event_objects.where(plantype: 'dog').first
#event_object ||= #event_entry.event_objects.build(plantype: dog)
In this last example, we try to find an existing object by getting an array of matching records and asking for the first item. If there are no items, #event_object will be nil.
Then we use the ||= operator that says "assign the value on the right if this is currently set to a falsy value". And nil is falsy. So if it's nil we can build the object form the association it should belong to. And we can preset it's attributes while we are at it.
Why not use built in query methods like find_or_create_by or find_or_initialize_by
#event_object = #event_entry.event_objects.find_or_create_by(plantype:'dog')
This will find an #event_entry.event_object with plantype = 'dog' if one does not exist it will then create one instead.
find_or_initialize_by is probably more what you want as it will leave #event_object in an unsaved state with just the association and plantype set
#event_object = #event_entry.event_objects.find_or_initialize_by(plantype:'dog')
This assumes you are looking for a single event_object as it will return the first one it finds with plantype = 'dog'. If more than 1 event_object can have the plantype ='dog' within the #event_entry scope then this might not be the best solution but it seems to fit with your description.

How to check if a key exists in a Ruby hash?

I am using search of Net::LDAP, the returned entry is something like this.
#<Net::LDAP::Entry:0x7f47a6491c00
#myhash=
{:loginshell=>["/bin/bash"],
:cn=>["M... R..."],
:homedirectory=>["/mnt/home/m..."],
:uid=>["m..."],
:userpassword=>["{CRYPT}$1$3zR/C...$R1"],
...
}>
I tried to do the following, but failed.
(1)
e = entry.to_hash
e.has_key? "uid"
(2)
entry.has_key? "uid"
The first error says "to_hash" undefined, the second "has_key" undefined. Then I really don't know how to do it, basically I want to find if "uid" is present and if so get its correspondent value.
Thank you very much for the tip.
BTW, it only responds to "entry.uid", but if the search key is provided as a string, how to do that? for example,
def get_value(key)
if entry has key
return key's value
end
end
:uid is a Symbol. That's not a String.
try this:
e.has_key? :uid
The key "uid" doesn't exist. Try
e = Entry.new.myhash
e.has_key?(:uid)
That should return true. If that gives you an error, the problem might lie in your class. Make sure that myhash is defined in the initialize method, and that you use a getter method (or attr_reader) to be able to access the variable. You could use
attr_reader :myhash
right before the initialize method.

How do I elegantly handle nil cases in my array assignment - Ruby?

So I am pushing some elements on my array like this:
upd_city_list << [ j.children[0].text.strip!.gsub(/\s+\W/, ''), j.children[1].text, j.children[1][:href] ]
The above is in an iterator (hence the use of j).
The issue is that from time to time, the j.children[0].text turns up as nil, and Ruby doesn't like that.
I could add a bunch of if statements before this assignment, but that seems a bit inelegant to me.
How do I handle nil cases in this situation in an elegant way?
One possible solution is, when there is a nil value, just push the string none onto the array....but what would that look like?
Thanks.
Edit1:
This is the error I am getting:
NoMethodError: private method ‘gsub’ called for nil:NilClass
The real problem is that strip! returns nil when there are no changes to the string. Your text method is returning a string, it is your strip! method is returning nil. I don't know why it does this. I dislike it, too.
This case of the problem will go away if you just change strip! to strip
In a more general sense, you might create an object to return the array for you. You don't want to go changing (what I assume is) Nokogiri, but you can wrap it in something to hide the train wrecks that result.
You should replace j.children[0].text.strip! with one of two things:
(j.children[0].text || 'none').strip
or
j.children[0].text.to_s.strip
These will, of course, have different effects when the text is nil. I think your ACTUAL problem is that strip! was returning nil, and that should have been obvious to you from the error message.
This might be the case for one to use null object programming pattern. Nil is not a good null object. Try reading here and here. Null object is the elegant way.
nil or a_string will be a_string
so what about (j.children[0].text or 'none')
If you're in rails, this is a great use for the try method.
Also seems that your strip and gsub are redundent. Please consider this implementation:
descriptive_name_1 = j.children[0].text.try(:strip)
descriptive_name_2 = j.children[1].text
descriptive_name_3 = j.children[1][:href]
updated_city_list << [ descriptive_name_1 , descriptive_name_2, descriptive_name_3 ]
w/o try
descriptive_name_1 = j.children[0].text.to_s.strip
descriptive_name_2 = j.children[1].text
descriptive_name_3 = j.children[1][:href]
updated_city_list << [ descriptive_name_1 , descriptive_name_2, descriptive_name_3 ]
If you're in the rails environment you could try try method: https://github.com/rails/rails/blob/82d41c969897cca28bb318f7caf301d520a2fbf3/activesupport/lib/active_support/core_ext/object/try.rb#L50

How to access a property of an array in Ruby

I have this object of class Array
>> answers_to_problem
=> [#<Answer id: 807, problem_id: 1, player_id: 53, code: "function y = times2(x
)\r\n y = 2*x;\r\nend", message: nil, score: 12, output: nil, hide: nil, create
d_at: "2010-02-02 11:06:49", updated_at: "2010-02-02 11:06:49", correct_answer:
nil, leader: nil, success: true, cloned_from: nil>]
For doing a binary check, I need access to the success field. I am not sure I am even using the right terminology here so I can not search how to access it.
answer_to_problems was found this way:
answers_to_problem = Answer.find_all_by_problem_id_and_player_id(current_problem,player_id)
Ultimately, I want to do this check:
is_correct = (answers_to_problem.success == true)
That isn't a property of the array — it's a property of the object in the array. So you'd so answers_to_problem[0].success to access the success attribute of the first object of the array.
Are you sure, you want to use find_all? If you know you'll only get one Answer back, you should use find without the all. That way you get a single Answer object instead of an array.
If you can get back more than one answer, do you want to check that all the answers are successful or just that one of them is?
You can do the former with: answers.all?(&:success) and the latter with answers.any?(&:success).
A bit outside the question here, but:
is_correct = (answer_to_problem.success == true)
Here you are doing an assignment and a truth check which are not really needed.
is_correct is here just reflecting whatever answer_to_problem.success would be. Shorten:
answer_to_problem.success == true
Now you're still performing a comparison to get a boolean value which you already have. Shorten:
answer_to_problem.success
There is a statement which you can use in the same manner you'd use is_correct. To make it read even better you could do:
class Answer
def correct?
success
end
end
And just use answer_to_problem.correct?

Resources