如何在Ruby中编写嵌套的if / then语句

时间:2017-05-02 17:23:52

标签: ruby if-statement

我应该

  

定义一个方法,three_digit_format(n),接受一个整数n作为参数。假设n

我一直在修改以下代码的版本,但我总是遇到错误。有人可以建议吗?

def three_digit_format(n)
  stringed = n.to_s
  stringed.size
  if stringed.size > 2
    return stringed
  end
  elsif stringed > 1
    return "0" + stringed
  end
  else 
    return "00" + stringed
  end
end
puts three_digit_format(9)

4 个答案:

答案 0 :(得分:3)

Array.from

您可以使用rjust

rjust
  

如果integer大于str的长度,则返回一个新的String   str右对齐的长度整数,用padtr填充;   否则,返回str。

您的代码

问题

如果您让文本编辑器缩进代码,您可能会发现错误:

n.to_s.rjust(3, '0')

解决方案

def three_digit_format(n) stringed = n.to_s stringed.size if stringed.size > 2 return stringed end elsif stringed > 1 # <- elsif shouldn't be here return "0" + stringed end else return "00" + stringed end end puts three_digit_format(9) ifelsif属于同一个表达式:表达式的末尾只应该有一个else,而不是每个语句。

end

答案 1 :(得分:2)

正如一些人所指出的,这个功能完全没有意义,因为有几种内置的方法可以做到这一点。这里最简洁:

def three_digit_format(n)
  '%03d' % n
end

强迫你重新发明工具的练习只会让我上瘾。这不是编程的内容。学习成为一名有效的程序员意味着知道什么时候有一个可以完成工作的工具,何时需要结合使用多个工具,或者除了制作自己的工具之外别无选择。太多的程序员立即开始编写自己的工具,忽略了更优雅的解决方案。

如果您因学术限制而致力于这种方法,那为什么不呢?

def three_digit_format(n)
  v = n.to_s

  while (v.length < 3)
    v = '0' + v
  end

  v
end

还是这样的?

def three_digit_format(n)
  (n + 1000).to_s[1,3]
end

在这种情况下,0-999表格的值将呈现为"1000" - "1999",您可以删除最后三个字符。

由于这些练习往往是荒谬的,为什么不把它带到荒谬的极限呢?

def three_digit_format(n)
  loop do
    v = Array.new(3) { (rand(10) + '0'.ord).chr }.join('')

    return v if (v.to_i == n)
  end 
end

如果您正在教授有关if语句以及如何附加elsif条款的内容,那么在有意义的语境中呈现这些语句是有意义的,而不是像这样设计的内容。例如:

if (customer.exists? and !customer.on_fire?)
  puts('Welcome back!')
elsif (!customer.exists?)
  puts('You look new here, welcome!')
else
  puts('I smell burning.')
end

if语句链是如此多的方式是不可避免的,它是如何最终实现业务逻辑的。在不适当的情况下使用它们是代码最终变得丑陋,Rubocop或Code Climate会给你一个失败的等级。

答案 2 :(得分:0)

正如其他人所指出的那样,rjust和应用格式'%03d' % n的方式也是如此。

但是如果你必须坚持到目前为止所学到的知识,我想知道你是否已经介绍过case陈述?

def three_digit_format(n)
  case n
  when 0..9
    return "00#{n}"
  when 10..99
    return "0#{n}"
  when 100..999
    return "#{n}"
  end
end

我认为它比连续的if陈述更清晰。

答案 3 :(得分:0)

这是我的旋转:

def three_digit_format(n)
  str = n.to_s
  str_len = str.length
  retval = if str_len > 2
             str
           elsif str_len > 1
             '0' + str
           else 
             '00' + str
           end
  retval
end

three_digit_format(1)   # => "001"
three_digit_format(12)  # => "012"
three_digit_format(123) # => "123"

可以减少为:

def three_digit_format(n)
  str = n.to_s
  str_len = str.length
  if str_len > 2
    str
  elsif str_len > 1
    '0' + str
  else 
    '00' + str
  end
end

应该完成的方式是利用String格式:

'%03d' % 1   # => "001"
'%03d' % 12  # => "012"
'%03d' % 123 # => "123"