arrays - Why does this refactored ruby method return nil? -


i wrote method in class float takes float (seconds) , converts countdown timer. code works fine when write this:

class float   def to_countdown     (self % 60) == 1 ? cd_sec = "#{(self % 60).to_i} second" : ( (self % 60).to_i == 0 ? cd_sec = "" : cd_sec = "#{(self % 60).to_i} seconds" )     ((self/60) % 60) == 1 ? cd_min = "#{((self/60) % 60).to_i} minute" : ( ((self/60) % 60).to_i == 0 ? cd_min = "" : cd_min = "#{((self/60) % 60).to_i} minutes" )     (self/3600) == 1 ? cd_hour = "#{(self/3600).to_i} hour" : ( (self/3600).to_i == 0 ? cd_hour = "" : cd_hour = "#{(self/3600).to_i} hours" )     (self/(60*60*24)) == 1 ? cd_day = "#{(self/(60*60*24)).to_i} day" : ( (self/(60*60*24)).to_i == 0 ? cd_day = "" : cd_day = "#{(self/(60*60*24)).to_i} days" )     countdown = [cd_day, cd_hour, cd_min, cd_sec].reject! {|c| c == nil}     return countdown.to_sentence   end end  509330.546146.to_countdown => "x days, y hours, z minutes, , seconds" 

i wanted refactor it. end results was:

class float   def to_countdown     s,m,h,d = (self % 60),((self/60) % 60),((self/3600)%24),(self/(60*60*24))     s == 1 ? cd_sec  = "#{s.to_i} second" : ( s.to_i == 0 ? cd_sec  = "" : cd_sec  = "#{s.to_i} seconds" )     m == 1 ? cd_min  = "#{m.to_i} minute" : ( m.to_i == 0 ? cd_min  = "" : cd_min  = "#{m.to_i} minutes" )     h == 1 ? cd_hour = "#{h.to_i} hour"   : ( h.to_i == 0 ? cd_hour = "" : cd_hour = "#{h.to_i} hours" )     d == 1 ? cd_day  = "#{d.to_i} day"    : ( d.to_i == 0 ? cd_day  = "" : cd_day  = "#{d.to_i} days" )     countdown = [cd_day, cd_hour, cd_min, cd_sec].reject! {|c| c == nil}     return countdown.to_sentence   end end 

when try refactorized version, get:

509330.546146.to_countdown => **undefined method `to_sentence' nil:nilclass>.**  

which means countdown nil. did wrong in refactored version?

replace this

countdown = [cd_day, cd_hour, cd_min, cd_sec].reject! {|c| c == nil} 

with this

countdown = [cd_day, cd_hour, cd_min, cd_sec].compact 

also, you're using bang version. mutates array in-place , can return nil. if want keep using reject, use regular version (non-bang).


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -