Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUBY

ruby check if hash has method before calling it

# Use .try(:key) to conditionally access hash keys or methods
attr = my_hash.try(:key1)

# You can chain together multiple try()'s
attr = my_hash.try(:key1).try(:key2)

# If you want to access a value in a hash value you can use ternary operators
attr = my_hash.try(:key1) ? my_hash.key1["key2"] : nil
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #ruby #check #hash #method #calling
ADD COMMENT
Topic
Name
4+6 =