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