Ruby on rails 字符串不匹配错误
我想从我的另一个站点解析一些项目。当我添加字符串时Ruby on rails 字符串不匹配错误,ruby-on-rails,ruby,json,parsing,console,Ruby On Rails,Ruby,Json,Parsing,Console,我想从我的另一个站点解析一些项目。当我添加字符串时 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
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
我做错了什么?
t.body
现在是字符串对象
要替换字符串中出现的所有文本,请使用gsub
或gsub代码>
t.body.gsub!("Some text", "Other text")
添加
为了回答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)
t.body
现在是字符串对象
要替换字符串中出现的所有文本,请使用gsub
或gsub代码>
t.body.gsub!("Some text", "Other text")
添加
为了回答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)
为什么它不应该工作<代码>s='foo';s['oo']='aa';放置s代码>打印faa
@toro2k,[]
仅在第一个元素上工作。s=‘fooo’;s['oo']='aa';放置s;将输出“faaoo”s='foooo';s、 gsub('oo','aa');#=>'当然是faaaa'
@BillyChan,但我不明白为什么OP code中的索引器
会被提升。为什么它不应该工作<代码>s='foo';s['oo']='aa';放置s代码>打印faa
@toro2k,[]
仅在第一个元素上工作。s=‘fooo’;s['oo']='aa';放置s;将输出“faaoo”s='foooo';s、 gsub('oo','aa');#=>'当然是faaaa'
@BillyChan,但我不明白为什么OP code中的索引器
会被提出。