重载 ActiveSupport 的默认 to_sentence 行为
ActiveSupport 提供了很好的方法to_sentence
。因此,
require 'active_support'
[1,2,3].to_sentence # gives "1, 2, and 3"
[1,2,3].to_sentence(:last_word_connector => ' and ') # gives "1, 2 and 3"
最好您可以更改最后一个单词连接器,因为我不喜欢有多余的逗号。但它需要太多额外的文本:44 个字符而不是 11 个!
问题:将 :last_word_connector
的默认值更改为 ' 和 '
的最像 ruby 的方法是什么?
ActiveSupport offers the nice method to_sentence
. Thus,
require 'active_support'
[1,2,3].to_sentence # gives "1, 2, and 3"
[1,2,3].to_sentence(:last_word_connector => ' and ') # gives "1, 2 and 3"
it's good that you can change the last word connector, because I prefer not to have the extra comma. but it takes so much extra text: 44 characters instead of 11!
the question: what's the most ruby-like way to change the default value of :last_word_connector
to ' and '
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嗯,它是可本地化的,因此您只需指定默认 'en' 值 ' 和 ' < code>support.array.last_word_connector
请参阅:
来自:conversion.rb
分步指南:
首先,创建一个 Rails 项目
接下来,编辑 en.yml 文件: vim config/locales/en.yml
最后,它可以工作:
Well, it's localizable so you could just specify a default 'en' value of ' and ' for
support.array.last_word_connector
See:
from: conversion.rb
Step by step guide:
First, Create a rails project
Next, edit your en.yml file: vim config/locales/en.yml
Finally, it works:
作为一般如何重写方法的答案,此处< /a> 提供了一个很好的方法。它不会遇到与别名技术相同的问题,因为没有剩余的“旧”方法。
在这里,您可以如何使用该技术来解决您的原始问题(使用 ruby 1.9 进行测试)
您可能还需要阅读 UnboundMethod 如果上面的代码令人困惑。请注意,old_to_sentence 在 end 语句之后超出了范围,因此对于将来使用 Array 来说这不是问题。
As an answer to how to override a method in general, a post here gives a nice way of doing it. It doesn't suffer from the same problems as the alias technique, as there isn't a leftover "old" method.
Here how you could use that technique with your original problem (tested with ruby 1.9)
You might also want read up on UnboundMethod if the above code is confusing. Note that old_to_sentence goes out of scope after the end statement, so it isn't a problem for future uses of Array.