![](/img/trans.png)
[英]String.force_encoding() in Ruby 1.8.7 (or Rails 2.x)
[英]Extending the “String” Class in Rails 2.x
我正在這樣寫String類的擴展:
#/lib/string.rb
Class String
def linkme
return self.gsub("[/link]", "</a>").gsub("[link=", "<a href='").gsub("]", "' target='_new'>")
end
end
但是,當我在控制台中調用它時,得到以下信息:
>>require 'lib/string'
SyntaxError: ./lib/string.rb:5: syntax error, unexpected kEND, expecting $end
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /home/path/to/vendor/rails/activesupport/lib/active_support/dependencies.rb:153:in `require'
from /home/path/to/vendor/rails/activesupport/lib/active_support/dependencies.rb:521:in `new_constants_in'
from /home/path/to/vendor/rails/activesupport/lib/active_support/dependencies.rb:153:in `require'
from (irb):11
我認為這應該在理論上可行,因為我沒有任何...
<geek_humor> loose "end"s </geek_humor>
這是我真正嘗試在Ruby中擴展此類的第一次嘗試,我認為我做得不錯,但是也許S / O社區可以幫助我總結一下。
這對你有用
class String
def linkme
self.gsub("[/link]", "</a>").gsub("[link=", "<a href='").gsub("]", "' target='_new'>")
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.