编辑:我通过使用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
3条答案
按热度按时间kr98yfug1#
String#lstrip
(或String#lstrip!
)是您所追求的。更多关于你的代码的评论:
delete_if {|x| x == ""}
可以替换为delete_if(&:empty?)
1.除了你想要
reject!
,因为delete_if
只会返回一个不同的数组,而不是修改现有的数组。words.each {|e| e.lstrip!}
可以替换为words.each(&:lstrip!)
1.如果在Windows机器上阅读Windows样式的文本文档,或者在Unix机器上读取Unix样式的文档,
delete("\r")
应该是多余的split(",")
可以替换为split(", ")
或split(/, */)
(如果最多有一个空格,则为/, ?/
)所以现在看起来像:
如果你有样本文本,我可以给予你更多的建议。
编辑:好的,开始:
使用的方法是
String#split
、Enumerable#map
、Enumerable#reject
和Array#flatten
。Ruby也有解析逗号分隔文件的库,但我认为它们在1.8和1.9之间有点不同。
sulc1iza2#
删除两个白色...
huwehgph3#
strip
方法在问题和一些注解中提到,但在单独的答案中也值得一提。该方法是删除了前导和尾随空格的str的副本.我认为这是最优雅的方法。有关信息,请参见https://apidock.com/ruby/String/strip