anakin
anakin

Reputation: 365

Assistance with ruby def

So, I'm new to ruby and very curious about it. I'm comming from python. in python I would do this to see if something was present in a dictionary.

dictionary = dict()
dictionary['key'] = 5
def inDictionary(key):
    if key in dictionary:
       execute code
    else:
        other code

Rather simple for me, in ruby on the other hand how would I do this? i've been trying stuff like

dictionary = Hash.new
dictionary['key'] = 5
def isDictionary(key)
    if dictionary.has_key?(key)
       puts 'has key'
    end
end

I get the error, isDictionary undefined local variable or method "dictionary". What am I doing wrong, and thanks in advance.

Upvotes: 1

Views: 98

Answers (2)

Raghu
Raghu

Reputation: 2563

Try this

@dictionar­y = Hash.­new
@dictionar­y['key'] = 5
def isDic­tionary(ke­y)
    if @dict­ionary.has­_key?(key)­
       puts 'has key'
    end
end

isDictionary("key")

What I have done is I have enhanced the scope of the dictionary variable by converting it into a instance variable @dictionary.

Upvotes: 1

raina77ow
raina77ow

Reputation: 106453

In Ruby, def, class, and module keywords start new local scopes. That means dictionary variable (defined as a local) is not accessible in this isDictionary function, as the latest has its own scope.

Of course, you can mark your variable with $ sigil to make it global instead, but you'd better not to. The whole point of Ruby is making objects - collections of data and methods to process/transform that data - as 'innate' as possible.

In this case the most natural solution would be to define class Dictionary, make dictionary its instance variable (with @ sigil), then access this variable in class method isDictionary.

Upvotes: 5

Related Questions