Ruby:删除字符串开头的空格字符

uubf1zoe  于 2023-06-22  发布在  Ruby
关注(0)|答案(3)|浏览(123)

编辑:我通过使用strip!remove leading and trailing whitespaces as I show in this video解决了这个问题。然后,我通过迭代并添加空白来恢复数组中每个字符串末尾的白色。这个问题与“dupe”不同,因为我的意图是在结尾保留空白。不过,脱吧!将删除前导和尾随空格(如果这是您的意图)。(我本来会把这个作为一个答案,但由于这被错误地标记为一个欺骗,我只能编辑我原来的问题,包括这个。)
我有一个单词数组,我试图删除任何可能存在于单词开头而不是结尾的空格。rstrip!只处理字符串的结尾。我想删除字符串开头的空格。

example_array = ['peanut', ' butter', 'sammiches']
desired_output = ['peanut', 'butter', 'sammiches']

正如您所看到的,并不是数组中的所有元素都有空格问题,因此我不能像删除所有元素都以单个空格字符开头的字符那样删除第一个字符。
完整代码:

words = params[:word].gsub("\n", ",").delete("\r").split(",")
words.delete_if {|x| x == ""}
words.each do |e|
  e.lstrip!
end

用户可以在表单上输入的示例文本:

Corn on the cob,
Fibonacci,
StackOverflow
Chat, Meta, About
Badges
Tags,,
Unanswered
Ask Question
kr98yfug

kr98yfug1#

String#lstrip(或String#lstrip!)是您所追求的。

desired_output = example_array.map(&:lstrip)

更多关于你的代码的评论:

  1. delete_if {|x| x == ""}可以替换为delete_if(&:empty?)
    1.除了你想要reject!,因为delete_if只会返回一个不同的数组,而不是修改现有的数组。
  2. words.each {|e| e.lstrip!}可以替换为words.each(&:lstrip!)
    1.如果在Windows机器上阅读Windows样式的文本文档,或者在Unix机器上读取Unix样式的文档,delete("\r")应该是多余的
  3. split(",")可以替换为split(", ")split(/, */)(如果最多有一个空格,则为/, ?/
    所以现在看起来像:
words = params[:word].gsub("\n", ",").split(/, ?/)
words.reject!(&:empty?)
words.each(&:lstrip!)

如果你有样本文本,我可以给予你更多的建议。

编辑:好的,开始:

temp_array = text.split("\n").map do |line|
  fields = line.split(/, */)
  non_empty_fields = fields.reject(&:empty?)
end
temp_array.flatten(1)

使用的方法是String#splitEnumerable#mapEnumerable#rejectArray#flatten
Ruby也有解析逗号分隔文件的库,但我认为它们在1.8和1.9之间有点不同。

sulc1iza

sulc1iza2#

> ' string '.lstrip.chop
=> "string"

删除两个白色...

huwehgph

huwehgph3#

strip方法在问题和一些注解中提到,但在单独的答案中也值得一提。该方法是删除了前导和尾随空格的str的副本.我认为这是最优雅的方法。

' Hello there '.strip   #=> "Hello there"

有关信息,请参见https://apidock.com/ruby/String/strip

相关问题