I want to return nil when Ruby makes the string numeric.

Asked 2 years ago, Updated 2 years ago, 45 views

When converting a string to a numeric value in ruby, I think you should use "100".to_i.

If "100a".to_i" is not a number, convert it to that point and
"Or, I think ""aa".to_i"" is the specification to return 0

"

I would like to create a method that returns nil if it contains characters.

As shown in the code below, it would be easy to pick it up with rescue, but
Is there any way not to use rescue?The code is not so cool...

 Integer("aa") rescunil

ruby

2022-09-30 20:45

3 Answers

There may be some ways not to use rescue, but

 Integer(str) rescue

is a clear and concise code that clearly communicates with almost everyone who can read and write Ruby, so you shouldn't do anything unnecessary.

As the official reference Time.parse also has a use case, the latter rescue is a common use in such cases.


2022-09-30 20:45

If you create a method with Integer(str)rescunil,

irb(main): 009:0>def to_i(str)
irb(main) : 010:1> Integer(str) rescue
irb(main): 011:1>end
=>nil
irb(main): 012:0>to_i "a"
=>nil
irb(main): 013:0>to_i "10a"
=>nil
irb(main): 014:0>to_i "10"
=>10

↑That's all right, but

irb(main): 015:0>to_i "010"
=>8
irb(main): 016:0>to_i "0x10"
=>16

↑This may not be the intended behavior.

So I thought it would be better to play it with regular expressions.

irb(main): 022:0>def to_i(str)
irb(main): 023:1>str.to_if str=~/\A-?(?\d|[1-9]\d+)\z/
irb(main): 024:1>end
=>nil
irb(main): 025:0>to_i "a"
=>nil
irb(main): 026:0>to_i "10a"
=>nil
irb(main): 027:0>to_i "10"
=>10
irb(main): 028:0>to_i "0x10"
=>nil
irb(main): 029:0>to_i "010"
=>nil

Please refer to it.


2022-09-30 20:45

str="100a"
str=~/^[0-9]+$/?str.to_i:nil


2022-09-30 20:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.