2014-10-02 76 views
1

我得到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 

回答

1

名称是一个数组,你有两个选择:

选项A:

给全称数组的元素:

def fullname(elem)  
    first(elem) + last(elem) 
end 

和呼叫它与

C.fullname(p.first) 

例如

选项B:

假设它总是阵列的全称第一元件

def fullname(p) 
    name=p["name"].first 
    first(name) + last(name) 
end 

不要被Array.first混淆这是阵列[ 0]和你的'第一'函数

+0

@sawa这是因为解释器试图将字符串(“第一”)转换为数组中的索引。 [1,2,3] [“name”]也会发生同样的情况 – tomsoft 2014-10-02 09:43:38

+0

我的评论应用于编辑之前陈述的OP问题。现在,问题已经改变,你的答案没有问题。我没有意识到,当我给你写评论时,我甚至不知道你的答案是在编辑之前还是之后发布的。 – sawa 2014-10-02 09:47:18

1

h["name"]结果是name = [{"first" => "first ", "last" => "last"}],其是一个数组。您不能申请name["first"]name["last"]。传递给数组的参数必须是整数。

0

"name"是一个数组。 fullname(p)应该读

first(p["name"][0]) + last(p["name"][0])