【问题标题】:Why does output of faker::lorem produce dashes at the beginning of the string?为什么 faker::lorem 的输出会在字符串的开头产生破折号?
【发布时间】:2012-08-26 13:22:52
【问题描述】:

使用faker gem 和rails 来生成一些假数据。当我使用 faker::lorem 时,输出包括字符串前面的破折号。

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
    7.times do |l|
      line = Line.create!(sentence: Faker::Lorem.sentences(2))
    end
  end
end

喜欢:

---
- Odit consectetur perspiciatis delectus sunt quo est.
- Tempore excepturi soluta aliquam perferendis.

知道为什么这个函数返回带有破折号的 Lorem 吗?去除它们的最简单方法是什么?

【问题讨论】:

  • 我想我明白了。 Lorem.sentences 返回一个数组。当我在最后添加 .join(" ") 时,破折号消失了,它读取正确。当您尝试将数组放入字符串时,一定会出现破折号。
  • 转成字符串时其实就是gem生成的YAML。

标签: ruby-on-rails faker lorem-ipsum


【解决方案1】:

正如 Kevin 和 Deefour 在 cmets 中提到的,Faker::Lorem 返回一个数组。

由于我们要求 Ruby 将其存储在字符串中,因此 Ruby 根据 YAML 的指南对其进行解释,这是一种在文本中表示数据结构的方式。

如果您遇到此问题,最简单的解决方法是使用 Ruby 内置的数组到字符串的转换方法.join(x),它将字符串 x 作为要添加的分隔符。

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 2021-04-02
    • 2011-01-26
    • 1970-01-01
    • 2021-05-01
    • 2023-04-06
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多