Reputation: 11
I feel like I'm overlooking something here. When I try to use the Hash.key(keytolookfor) method, I get an error.
Is this method deprecated?
pete@Vader:~/tmp$ ruby -v
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-linux]
pete@Vader:~/tmp$ ./hashtest.rb
./hashtest.rb:8: undefined method `key' for {"firstkey"=>"firstvalue", "secondkey"=>"secondvalue"}:Hash (NoMethodError)
pete@Vader:~/tmp$
The script is as follows.
#!/usr/bin/ruby
testHash = Hash.new
testHash["firstkey"] = "firstvalue"
testHash["secondkey"] = "secondvalue"
if testHash.has_value?("secondvalue")
keyvalue = testHash.key("secondvalue")
puts "match found with key #{keyvalue}"
else
puts "no match found"
end
Upvotes: 1
Views: 257
Reputation: 16507
Use the heap record for script as follows:
#/usr/bin/env ruby
This picks up the default ruby version specified by the system, rvm
, or rbenv
. Since Ruby 1.8.7 has no Hash#key
, make sure that you're running at least Ruby 1.9.1:
$ /usr/bin/ruby -v
1.9.1p0
Alternatively, use Hash#[]
instead:
keyvalue = testHash["secondvalue"]
Upvotes: 0
Reputation: 9225
My wild guess is that your system ruby /usr/bin/ruby
is 1.8.7 which doesn't have Hash#key
method. ruby -v
most probably shows rvm
version which is located in ~/.rvm/...
, but first line in your script calls /usr/bin/ruby
.
Upvotes: 2