in Ruby, why I need to define a hash, but don't need to define variables?
I mean, I don't declare
my_var = new variable
o开发者_如何学运维r something like that. I just go with
my_var = 1;
Similarly, why can't I just
books["War and peace"] = :masterpiece
Why I need to define in advance?
books = {}
books["War and peace"] = :masterpiece
calls the []=
method on books
with "War and peace"
and :masterpiece
as its arguments. If books
doesn't exist, you can't call a method on it.
Or to approach the question a different way: If ruby did do some magic to automatically initialize variables, when you use []=
on them, how should ruby know that you want books
to be a hash in the above example? Any class can have []
and []=
operators which accept strings as an index.
Doing:
my_var = 1
Is defining and assigning the local variable. With a hash it could be done like this:
books = { 'War and Peace' => :masterpiece }
精彩评论