我得到TypeError: no implicit conversion of String into Integer
无法弄清楚这里有什么问题。如何获取JSON对象的部分
require 'json'
h = '{"name":[{"first":"first ", "last":"last"}], "age":2}'
h = JSON.parse(h)
class C
def fullname(p)
first(p["name"]) + last(p["name"])
end
def age(p)
p["age"]
end
private
def first(name)
name["first"]
end
def last(name)
name["last"]
end
end
C.new.age(h) #=> 2
C.new.fullname(h) #=> TypeError: no implicit conversion of String into Integer
@sawa这是因为解释器试图将字符串(“第一”)转换为数组中的索引。 [1,2,3] [“name”]也会发生同样的情况 – tomsoft 2014-10-02 09:43:38
我的评论应用于编辑之前陈述的OP问题。现在,问题已经改变,你的答案没有问题。我没有意识到,当我给你写评论时,我甚至不知道你的答案是在编辑之前还是之后发布的。 – sawa 2014-10-02 09:47:18