理解哈希

Understanding hashes

一个练习说:

Create three hashes called person1, person2, and person3, with first and last names under the keys :first and :last. Then create a params hash so that params[:father] is person1, params[:mother] is person2, and params[:child] is person3. Verify that, for example, params[:father][:first] has the right value.

我做到了

person1 = {first: "Thom", last: "Bekker"}
person2 = {first: "Kathy", last: "Bekker"}
person2 = {first: "Anessa", last: "Bekker"}

然后 params 中的散列 Rails

params = {}
params[:father] = person1
params[:mother] = person2
params[:child] = person3

现在我可以像这样询问父亲、母亲或child的名字或姓氏 params[:father][:first] 给我 "Thom".

是什么导致 params[:father][:first][:last] return 错误?有没有办法做到 return "Thom Bekker"?

我无法验证我想出的方法是否正确,有没有更好的练习方法?

为什么 symbol:symbol => 好?

在Ruby中,在Hash or other classes is actually using a method available for an object of that class (this one)上使用方括号。当您在示例中调用这些方法时,将调用这些方法中的每一个,并在调用下一个方法之前 return 其结果。所以,正如您所定义的那样:

  1. Calling [:father] on params returns the hash represented by person1
  2. [:first] is then called on {first: "Thom", last: "Bekker"}, returning the corresponding value in the hash, "Thom"
  3. [:last] is called on "Thom", which results in an error. Calling square brackets on a string with an integer between them can access the character in a string at that index (person1[:first][0] returns "T"), but "Thom" doesn't have a way of handling the :last symbol inside the square brackets.

有多种方法可以根据需要打印名称,最简单的方法之一是组合 person1:

中的字符串值

params[:father][:first] + " " + params[:father][:last] returns "Thom Bekker"

您的 Return 值是单个哈希对象

您误解了返回的对象类型。 params[:father] returns 单个 Hash object, not an Array 或哈希数组。例如:

params[:father]
#=> {:first=>"Thom", :last=>"Bekker"}

params[:father].class
#=> Hash

因此,您无法访问缺少的第三个元素(例如 :last),因为 params[:father][:first] 的值中没有这样的元素。

相反,您可以解构哈希:

first, last = params[:father].values
#=> ["Thom", "Bekker"]

或者做一些更深奥的事情,比如:

p params[:father].values.join " "
#=> "Thom Bekker"

关键是你必须访问Hash的values,或者先把它转换成一个Array,而不是直接把它当成一个Array然后试图索引到一次有多个值。

So here's my question, what exactly makes params[:father][:first][:last] return an error? Is there a way to make that return "Thom Bekker"?

这两个都可以

  1. params[:father][:first] + params[:father][:last]
  2. params[:father].values.join(' ')

但也许最好将它们视为嵌套结构:

father = params[:father]
name   = father[:first] + father[:last]
puts name

为了回答你的最后一个问题,假设 hashrocket =>symbol: 之间没有区别。这是一个你不需要长时间照顾的地方。也许大约 2 年级开始再次问这个问题,但为了学习,将它们视为等同的。

(完全公开,有差异,但这是一个你真的不想看到的神圣war)