2013-08-27 85 views
0

我想解析来自我的另一个站点的一些项目。当我添加一个字符串字符串不匹配错误

t.body["Some text"] = "Other text" 

它取代在身体的一些文本,出现错误:

IndexError in sync itemsController#syncitem 

string not matched 

的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 

我在做什么错?

回答

5

t.body现在是一个String对象。

要替换字符串一些文本的所有出现,使用gsubgsub!

t.body.gsub!("Some text", "Other text") 

添加

要回答关于为什么这样erorr,我查了一下,得知toro2k的评论,使用[]更换字符串中的东西将输出“索引错误”,如果这样的字符串doe不存在

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) 
+0

thx!这项工作! – Andrew

+0

为什么它不应该工作? 's ='foo'; s ['oo'] ='aa';放置;'打印'faa'。 – toro2k

+0

@ toro2k,'[]'仅适用于第一个元素。 s ='foooo'; s ['oo'] ='aa';放置;将输出“法奥” –