【问题标题】:Ruby 99 bottles of beer on the wall, DRY principleRuby 99 瓶啤酒上墙,DRY 原则
【发布时间】:2020-04-03 18:56:14
【问题描述】:

我想知道是否有办法避免在 Bottle_of_beer 变量上编写 .to_s 方法? (DRY原则)

bottles_of_beer = 99

while bottles_of_beer != 1

beer_left = bottles_of_beer - 1

bottles_of_beer = beer_left

puts bottles_of_beer.to_s + ' bottles of beer on the wall ' + bottles_of_beer.to_s + ' bottles of beer.'

puts 'Take one down and pass it around, ' + beer_left.to_s + ' of beer on the wall.'

end

if bottles_of_beer == 1

puts bottles_of_beer.to_s + ' bottle of beer on the wall, ' + bottles_of_beer.to_s + ' bottle of beer.'

puts 'Take one down and pass it around, no more bottles of beer on the wall.'
end

puts 'No more bottles of beer on the wall, no more bottles of beer.'

puts 'Go to the store and buy some more, 99 bottles of beer on the wall.'

我想知道是否有办法避免在 Bottle_of_beer 变量上编写 .to_s 方法?

【问题讨论】:

标签: ruby string variables methods dry


【解决方案1】:

通常,您会为此使用string interpolation,如果需要,它将自动使用to_s

puts "#{bottles_of_beer} bottles of beer on the wall #{bottles_of_beer} bottles of beer."

顺便说一句,您的代码通常会像这样实现:

puts 99.downto(2).map { |number_of_bottles|
  "#{number_of_bottles} bottles of beer on the wall #{number_of_bottles} bottles of beer.
Take one down and pass it around, #{number_of_bottles - 1} of beer on the wall."
}

puts 'Take one down and pass it around, no more bottles of beer on the wall.'
puts 'No more bottles of beer on the wall, no more bottles of beer.'
puts 'Go to the store and buy some more, 99 bottles of beer on the wall.'

【讨论】:

  • Donald Knuth 在他的文章"The Complexity of Songs" 中证明了这首歌的复杂度为O(log N)。 (您在一个地方缺少“瓶子”,尽管number_of_bottles #=> 2 时应该是“瓶子”。另外,对于 number_of_bottles
【解决方案2】:

从 Jorg 的想法开始,使用插值,但更多的是一种函数式方法,只是为了好玩:

def bottles_song(n)
  if n.zero?
    puts "No more bottles of beer on the wall, no more bottles of beer!\nGo to the store and buy some more, #{n} bottles of beer on the wall.\n"
    return
  end

  puts "#{n} #{ n != 1 ? 'bottles' : 'bottle'  } of beer on the wall, #{n} #{ n != 1 ? 'bottles' : 'bottle' } of beer.\nTake one down, pass it around, #{n != 1 ? (n-1) : 'no more'} #{ n != 1 ? 'bottles' : 'bottle' } of beer on the wall!\n"

  bottles_song(n-1)
end

提高了可读性,但它采用了其他方法,并不是真正的改进:)

def bottles_song(n)
  if n.zero?
    puts "No more bottles of beer on the wall, no more bottles of beer!\nGo to the store and buy some more, #{n} bottles of beer on the wall.\n"
    return
  end

  puts_bottles(n)
  bottles_song(n-1)
end

def puts_bottles(n)
  puts "#{n} #{ pluralize_bottle(n)  } of beer on the wall, #{n} #{ pluralize_bottle(n) } of beer.\nTake one down, pass it around, #{n != 1 ? (n-1) : 'no more'} #{ pluralize_bottle(n-1) } of beer on the wall!\n"
end

def pluralize_bottle(n)
  return 'bottles' if n != 1
  'bottle'
end

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 2021-04-27
    • 2018-07-17
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    相关资源
    最近更新 更多