2014-04-22 50 views
1

是否有可能在不使用任務的情況下編寫代碼段摘錄?紅寶石鏈接與爆炸

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

我一直在使用的方法砰版本嘗試,但不能用得很好,因爲他們返回nil如果操作沒有進行任何改變(而不是返回self)。

+2

不會'to_s' foi你的努力呢? –

+0

「使用歸因」是什麼意思? – sawa

+0

'to_s'用於將''nil''轉換爲''「''。這節省了一些錯誤處理的方式,並且是Ruby中使用的慣例。 – cenouro

回答

4

你必須點擊整個事情。所以它會是這樣的:

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

這不是我通常會推薦做的事情。即使你有突變的迫切需要,最好的代碼清晰度來自使用方法,他們設計的方式:

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

如果這是不方便的,考慮是否真的需要的突變。

+0

有趣的查克,儘管我幾乎可以爲任何包含「tap」的答案+1。我沒有想到在我希望刪除的情況下會返回剩餘的內容而不是刪除的內容。可是等等!你沒有把它塞入'@ name'。 –

2

如果你真的要避免分配你可以做到這一點:

self.name = 'This is a test ' 

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

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

非常有創意,@Uri,雖然這非常接近任務(如您選擇的斜體所示)。 –

1

對於一個班輪沒有(紅寶石)歸因和無龍頭:

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

如:

$ 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"