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的默认值更改为' and '的最类似红宝石的方法是什么?
发布于 2009-08-26 13:03:24
作为一般情况下如何重写方法的答案,post 这里提供了一种很好的方法。它不存在与别名技术相同的问题,因为没有剩余的“旧”方法。
在这里,您如何使用该技术来解决原来的问题(用ruby1.9进行测试)
class Array
old_to_sentence = instance_method(:to_sentence)
define_method(:to_sentence) { |options = {}|
options[:last_word_connector] ||= " and "
old_to_sentence.bind(self).call(options)
}
end如果上面的代码令人困惑,您也可能需要阅读UnboundMethod。请注意,old_to_sentence在end语句之后超出了作用域,因此对于数组的未来使用来说,这并不是一个问题。
发布于 2009-08-26 12:16:36
class Array
alias_method :old_to_sentence, :to_sentence
def to_sentence(args={})
a = {:last_word_connector => ' and '}
a.update(args) if args
old_to_sentence(a)
end
endhttps://stackoverflow.com/questions/1334168
复制相似问题