1

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.

anakin
  • 347
  • 3
  • 18
  • 1
    Thats because the scope of dictionary changes when you call it inside the isDictionary method. I would recommend creating a class dictionary and a isDictionary method within it so that all the instances that you spawn through that class with have isDictionary available to them .Hope this makes sense – Raghu Sep 18 '13 at 23:49

2 Answers2

5

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.

raina77ow
  • 99,006
  • 14
  • 190
  • 222
1

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.

Raghu
  • 2,515
  • 1
  • 17
  • 24