distance_of_time_in_words然后删除"约"这个词

Rub*_*tic 6 time ruby-on-rails ruby-on-rails-3

我有这个代码:

    = distance_of_time_in_words(Time.now, real_time + 0.seconds, true)
Run Code Online (Sandbox Code Playgroud)

Wich也产生如下:

about 15 hours
less than
Run Code Online (Sandbox Code Playgroud)

有没有办法从结果中删除"关于"这个词?已经搜索了很多,但找不到任何信息,这个功能本身很棒,它会把小时,分钟,秒等等扔掉,但是最糟糕的"约"必须去!谁知道怎么样?谢谢!

ste*_*her 15

由于distance_of_time_in_words使用了本地化密钥,您可以简单地覆盖它们,以便以I18n安全的方式实现您的目标:

配置/区域设置/ en.yml:

en:
  # Used in distance_of_time_in_words(), distance_of_time_in_words_to_now(), time_ago_in_words()
  datetime:
    distance_in_words:
      half_a_minute: "half a minute"
      less_than_x_seconds:
        one:   "1 second" # default was: "less than 1 second"
        other: "%{count} seconds" # default was: "less than %{count} seconds"
      x_seconds:
        one:   "1 second"
        other: "%{count} seconds"
      less_than_x_minutes:
        one:   "a minute" # default was: "less than a minute"
        other: "%{count} minutes" # default was: "less than %{count} minutes"
      x_minutes:
        one:   "1 minute"
        other: "%{count} minutes"
      about_x_hours:
        one:   "1 hour" # default was: "about 1 hour"
        other: "%{count} hours" # default was: "about %{count} hours"
      x_days:
        one:   "1 day"
        other: "%{count} days"
      about_x_months:
        one:   "1 month" # default was: "about 1 month"
        other: "%{count} months" # default was: "about %{count} months"
      x_months:
        one:   "1 month"
        other: "%{count} months"
      about_x_years:
        one:   "1 year" # default was: "about 1 year"
        other: "%{count} years" # default was: "about %{count} years"
      over_x_years:
        one:   "1 year" # default was: "over 1 year"
        other: "%{count} years" # default was: "over %{count} years"
      almost_x_years:
        one:   "1 year" # default was: "almost 1 year"
        other: "%{count} years" # default was: "almost %{count} years"
Run Code Online (Sandbox Code Playgroud)


klu*_*ump 10

distance_of_time_in_words(Time.now, real_time + 0.seconds, true).gsub('about ','')

这里了解更多信息

尝试帮助(将此代码放在app/helpers/application_helper.rb中)

def remove_unwanted_words string
  bad_words = ["less than", "about"]

  bad_words.each do |bad|
    string.gsub!(bad + " ", '')
  end

  return string
end
Run Code Online (Sandbox Code Playgroud)

不好的话,您可以定义要从该字符串中删除的字符串.用户喜欢这样:

<%= remove_unwanted_words distance_of_time_in_words(Time.now, real_time + 0.seconds, true) %>

  • 请注意 – 如果您需要将网站翻译成非英语语言,此解决方案会让您感到痛苦。 (2认同)