Today's the day

向软件大牛炫耀我会焊单片机,向硬件大牛炫耀我会写 Rails,向软硬件大牛炫耀我生物,向软硬件生物大牛炫耀我会折腾期货 -_-bbb

rake rails:update
犯迷糊了: 对 && 的错误理解

带有默认值的 to_i

galeki posted @ 2008年3月30日 20:24 in RoR with tags ruby , 5698 阅读

Ruby 中的 to_i 方法可以把对象转换成数字,"123".to_i 就返回 123,用来将用户输入的文本转换成数字非常实用。

不过如果对象无法转换成数字,to_i 就返回 0 了,假如我想在用户的输入无意义的情况下,取一个默认值 ( 比如 50 ),而不是 0,就要:

  1. if input.to_i == 0
  2.    return 50
  3. else
  4.    input.to_i
  5. end

这样的代码很让人郁闷……  更好的办法是利用 Ruby 方便的语法特性,定义一个 to_num 方法:

  1. module Kernel
  2.     def to_num(default=0)
  3.         self.to_i == 0 ? default : self.to_i
  4.     end
  5. end

这样,所有的对象都可以应用这个带有默认值的 to_num 方法了~

  1. irb > "123".to_num
  2. => 123
  3. irb > "abc".to_num
  4. => 0
  5. irb > "abc".to_num(50)
  6. => 50

完全可以取代 to_i 方法。

Jacqueline Johns 说:
2020年3月25日 12:52

An official click is a surd for the help of the parts for all people. An account of the essay typer reviews is held for the possible means for humans. THz turn is invited for all scores. The argument is invited for the help of the funded element and data for the use of the offers for humans.

anonymous 说:
2023年5月03日 20:01

This is helpful, nonetheless it can be crucial so that you can check out the following website: Pest Control Orlando

anonymous 说:
2023年5月03日 20:05

I use only high quality materials - you can see them at:  Oviedo Exterminator


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter