Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if property exists in object

Tags:

ruby

I spent a long time now trying to figure this myself with the help of other questions but failed so I REALLY need to ask this again

I have the following object in ruby

(...)
  :follow_request_sent: 
  :notifications:  
:coordinates: 
:place: 
:contributors: 
:favorite_count: 0
:entities:
  :hashtags:
  - :text: 
    :indices:
(...)

This is object X. What I want to do is check if x.place exists. I've tried barely EVERYTHING. any, ?, include?, with [hash], defined?, (...) but it ALWAYS throws an error "undefined method" when trying to access the property, whether it exists or not. It NEVER works and I don't understand why. This is twitter API btw. Does anyone imagine why? Please do not point me to another answers because basically they all failed.

like image 877
DigitalEvolution Avatar asked Aug 08 '15 20:08

DigitalEvolution


People also ask

How do you check if a property exists in an object?

We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.

How do you check if a property exists in an object angular?

Using myObject. hasOwnProperty('prop') is a great way of accessing the Object's keys directly, which does not look into the Object's prototype - hooray, this is great for specific use cases. hasOwnProperty returns a Boolean for us on whether a property exists.

How do you check if an object has a specific property in JavaScript?

The static Reflect.has() method works like the in operator as a function. If the property does not exist on the object, it will return the string undefined. Else it will return the appropriate property type.

How do you check if an object has a property in TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.


1 Answers

If you want to see if there is such a method:

x.respond_to?(:place)

If you want to see if there is an instance variable:

x.instance_variable_defined?(:@place)
like image 124
ndnenkov Avatar answered Sep 24 '22 00:09

ndnenkov