0
contacts_r = File.open("user_contacts.txt", "r")

user_contacts = []
contacts_r.readlines.each { |line|
  user_contacts << line.chomp
}

$c = Hash[user_contacts.map { |x| ["$#{x}_called", Array.new] } ]

When I try to add info in the desired array...

$c["#{name}_called"] << 1

I get a undefined method '<<' for nil:NilClass (NoMethodError)

when I use..

puts $c

the output looks like

{"$robert_called"=>[]}

I'm trying to make it look like

{"$robert_called"=>[1]}
2
  • 2
    What is name? If it's not "robert", the error is obvious. Your code otherwise looks okay. (I'd probably contract the whole thing into user_contacts = File.read(filename).lines.map(&:chomp) or the lazier user_contacts = File.open(filename) { |f| f.each_line.map(&:chomp) }, and use a hash with a default proc (c = Hash.new { |h, k| h[k] = [] }) so I don't have to initialise it at all... Also, beware global variables, they have a nasty habit of biting you in the behind. Commented Nov 10, 2015 at 6:17
  • by "#{name}" i just meant thats where the namesgo...its no actualy part of the code :\ @Amadan Commented Nov 10, 2015 at 8:02

1 Answer 1

1

You forgot to prepend $.

$c["$#{name}_called"] << 1
Sign up to request clarification or add additional context in comments.

2 Comments

...and $[k] => nil (i.e., the value of key k is nil) if the hash does not have a key k, so $c[k] << 1 becomes nil << 1. nil is the one and only instance of NilClass. NilClass has no instance method :<<, which means that nil has no method :<<. That's precisely what the error message is telling you. Study error messages carefully. Often they pinpoint the problem.
your right, I forgot to put the $ in the array name. And i'm still considerably new (not even a year) so I'll pay more attention to what the errors are saying, thanks. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.