如何在Ruby压扁

jei2mxaa  于 2023-01-25  发布在  Ruby
关注(0)|答案(6)|浏览(152)

我想在Ruby中使用squish。我在Ruby on Rails中发现了这个方法,但我想在Ruby中使用它,只是因为我没有使用Ruby on Rails。
你怎么能在Ruby里这么做。

" foo   bar    \n   \t   boo".squish # => "foo bar boo"
uidvcgyl

uidvcgyl1#

请尝试以下操作:

" foo   bar    \n   \t   boo".split.join(" ")
# => "foo bar boo"
brjng4g3

brjng4g32#

在Rails源代码中,将squish!添加到String

# File activesupport/lib/active_support/core_ext/string/filters.rb, line 16
def squish!
  gsub!(/\A[[:space:]]+/, '')
  gsub!(/[[:space:]]+\z/, '')
  gsub!(/[[:space:]]+/, ' ')
  self
end
u1ehiz5o

u1ehiz5o3#

我认为没有理由(重新)实现它而不使用ActiveSupport,您可以在没有整个Rails框架的情况下使用它:

require 'active_support/core_ext/string/filters'
" foo   bar    \n   \t   boo".squish
# => "foo bar baz"

或者,如果您真的不想使用Rails,可以使用Ruby Facets

require 'facets/string/squish'
" foo   bar    \n   \t   boo".squish
# => "foo bar baz"

更新嗯,也许,性能可能是一个原因。一个快速的基准:

require 'benchmark'

require 'facets/string/squish'

def squish_falsetru(s)
  s.strip.gsub(/s+/, ' ')
end

def squish_priti(s)
  s.split.join(' ')
end

# ActiveSupport's implementation is not included to avoid 
# names clashes with facets' implementation.
# It is also embarrassing slow!

N = 500_000
S = " foo   bar    \n   \t   boo"

Benchmark.bm(10) do |x|
  x.report('falsetru') { N.times { squish_falsetru(S) } }
  x.report('priti') { N.times { squish_priti(S) } }
  x.report('facets') { N.times { S.squish } }
end

                 user     system      total        real
falsetru     1.050000   0.000000   1.050000 (  1.047549)
priti        0.870000   0.000000   0.870000 (  0.879500)
facets       2.740000   0.000000   2.740000 (  2.746178)
ev7lccsx

ev7lccsx4#

>> " foo   bar    \n   \t   boo".strip.gsub(/\s+/, ' ')
=> "foo bar boo"
xmjla07d

xmjla07d5#

您可以自行实施:

def squish
  string = strip
  string.gsub!(/\s+/, ' ')
  string
end

它修改了Rails的squish!方法。

wlzqhblo

wlzqhblo6#

这将向Ruby String类添加一个行为类似于Rail的squish方法的方法:

class String
  def squish
    strip.gsub(/\s+/, ' ')
  end
end

示范:

$ irb
irb(main):001:1* class String
irb(main):002:2*   def squish
irb(main):003:2*     strip.gsub(/\s+/, ' ')
irb(main):004:1*   end
irb(main):005:0> end
=> :squish
irb(main):006:0> "  Help, I   am trapped  in a  computer  ".squish
=> "Help, I am trapped in a computer"

相关问题