ruby - Hashes and different syntax: getting nils as return values when trying to access key-values -
beginner programmer here who's been in couple of months.
assuming have block of code data structure:
users = { admin: "secret", admin2: "secret2", admin3: "secret3" }
when try access value specific key so: users[:admin]
, return value of nil
, if use syntax: users['admin']
, return value of "secret"
. why happen? aren't these 2 syntaxes supposed equivalent according documentation.
side question: when create .yml
file data structure, , try set this:
{ "admin" => "secret", "admin2" => "secret2", "admin3" => "secret3" }
i not able load ("parse") file , error:
did not find expected ',' or '}' while parsing flow mapping @ line 1 column 1
but block of code in beginning fine. again, thought syntax supposed equivalent or perform same function. why happen? think weakest point in coding @ point hashes because confuses me much.
thanks in advance!
@borsunho correct in stating :admin
, "admin"
not equivalent. if have come rails background out understanding ruby can confusing since params
hash not care. because params
special class called hashwithindifferentaccess
.
implementing not difficult besides question.
as yml file should be:
:admin: "secret" :admin2: "secret2" :admin3: "secret3"
this parse out same original hash
. syntax different yml way store data structures , independent of ruby or of syntax rules.
the leading colons mean symbol, otherwise keys parsed strings.
e.g.
require 'yaml' yml = <<yml :admin: "secret" :admin2: "secret2" :admin3: "secret3" yml yaml.load(yml) #=> {:admin=>"secret", :admin2=>"secret2", :admin3=>"secret3"} yml = <<yml admin: "secret" admin2: "secret2" admin3: "secret3" yml yaml.load(yml) #=> {"admin"=>"secret", "admin2"=>"secret2", "admin3"=>"secret3"}
Comments
Post a Comment