And*_*rew 0 ruby console parsing json ruby-on-rails
我想从我的另一个网站解析一些项目.当我添加一个字符串
t.body["Some text"] = "Other text"
Run Code Online (Sandbox Code Playgroud)
它取代了正文中的一些文字,出现了错误:
IndexError in sync itemsController#syncitem
string not matched
Run Code Online (Sandbox Code Playgroud)
LIB/sync_items.rb
require 'net/http'
require 'json'
require 'uri'
module ActiveSupport
module JSON
def self.decode(json)
::JSON.parse(json)
end
end
end
module SyncItem
def self.run
uri = URI("http://example.com/api/v1/pages")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
parsed_response = JSON.parse(response.body)
parsed_response.each do |item|
t = Page.new(:title => item["title"], :body => item["body"], :format_type => item["format_type"])
t.body["Some text"] = "Other text"
t.save
end
end
end
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
t.body 现在是一个String对象.
要替换字符串中所有出现的文本,请使用gsub或gsub!
t.body.gsub!("Some text", "Other text")
Run Code Online (Sandbox Code Playgroud)
加
要回复toro2k关于为什么这样的erorr的评论,我检查并学习,使用[]字符串替换某些东西将输出"索引错误",如果这样的字符串不存在
s = 'foo'
s['o'] = 'a'
#=> 'fao' Works on first element
s.gsub('o', 'a')
#=> 'faa' Works on all occurence
s['b'] = 'a'
#=> IndexError: string not matched. (Non-existing string will bring such error)
s.gsub('b', 'a')
#=> nil (gsub will return nil instead of exception)
Run Code Online (Sandbox Code Playgroud)