红宝石与爆炸链接

时间:2014-04-22 17:18:13

标签: ruby

是否可以在不使用作业的情况下编写此代码摘录?

self.name = self.name.to_s.squeeze(' ').strip

我尝试过使用bang版本的方法,但是如果操作没有执行任何更改(而不是返回nil),则返回self,因此无法使用。

3 个答案:

答案 0 :(得分:4)

你必须挖掘整个事情。所以它会是这样的:

str.tap {|x| x.squeeze!(' ')}.tap(&:strip!)

这不是我通常建议做的事情。即使你迫切需要变异,最好的代码清晰度来自于按照设计方式使用方法:

str.squeeze!(' ')
str.strip!

如果这样做不方便,请考虑您是否真的需要突变。

答案 1 :(得分:2)

如果确实想要避免分配,可以执行此操作:

self.name = 'This  is a    test  '

[['squeeze!', ' '], 'strip!'].each { |cmd| self.name.send(*cmd) }

self.name
# => "This is a test"

答案 2 :(得分:1)

对于没有(Ruby)归因且没有tap的单行:

a.name && (a.name.squeeze!(' ') || a.name).strip!

e.g:

$ irb
2.1.1 :001 > class A
2.1.1 :002?>   def name=(name)
2.1.1 :003?>     puts "setting name=#{name.inspect}"
2.1.1 :004?>     @name = name
2.1.1 :005?>     end
2.1.1 :006?>   attr_reader :name
2.1.1 :007?>   end
 => nil 
2.1.1 :008 > a = A.new
 => #<A:0x007fdc909d6df8> 
2.1.1 :009 > a.name = '  and   she    was  '
setting name="  and   she    was  "
 => "  and   she    was  " 
2.1.1 :010 > a.name && (a.name.squeeze!(' ') || a.name).strip!
 => "and she was" 
2.1.1 :011 > a.name
 => "and she was" 
2.1.1 :012 > a.name = 'and   she    was'
setting name="and   she    was"
 => "and   she    was" 
2.1.1 :013 > a.name && (a.name.squeeze!(' ') || a.name).strip!
 => nil 
2.1.1 :014 > a.name = 'and she was '
setting name="and she was "
 => "and she was " 
2.1.1 :015 > a.name && (a.name.squeeze!(' ') || a.name).strip!
 => "and she was"