This theme, exception handling
If you are faithful to the basics, you will answer with regular expression
, but I would like to answer with exception handling
to better understand *** Ruby ***.
Pattern if all three letters are numbers
ruby1.rb
s = gets.chomp
puts (/[0-9]{3}/ === s ? s.to_i * 2 : 'error')
s = gets.chomp
puts (s.match(/[0-9]{3}/) ? s.to_i * 2 : 'error')
Pattern if even one character is lowercase
ruby2.rb
s = gets.chomp
puts (/[a-z]/ === s ? 'error' : s.to_i * 2)
s = gets.chomp
puts (s.match(/[a-z]/) ? 'error' : s.to_i * 2)
Pattern if even one letter is other than a number
ruby3.rb
s = gets.chomp
puts (/[^0-9]/ === s ? 'error' : s.to_i * 2)
s = gets.chomp
puts (s.match(/[^0-9]/) ? 'error' : s.to_i * 2)
Ruby to_i (WA)
Pattern with to_i
applied directly
ruby4.rb
s = 'abc'
puts s.to_i # => 0
s = '42A'
puts s.to_i # => 42
Ruby Rational (AC)
Pattern with Rational
applied
ruby5.rb
s = gets.chomp
begin
Rational(s)
rescue
puts 'error'
else
puts s.to_i * 2
end
The control structure for exception handling is as follows.
rescue.rb
begin
#Processing that may cause an exception
[rescue [error_type,..] [=> evar] [then]
#What to do when an exception occurs
[else
#Processing when an exception does not occur]
[ensure
#Processing executed regardless of exceptions]
end
begin
ʻelse ʻensure
is optional.
Although it is Rational
that is not usually used, it is a class that handles rational numbers such as" 1/3 ".
to_r
interprets the first number, but Rational
seems to raise an exception well.
ruby6.rb
puts '0x8'.to_r # => 0/1
puts Integer('0x8') # => 8
puts Float('0x8') # => 8.0
puts Complex('0x8') # => ArgumentError
puts Complex('08i') # => 0+8i
Complex
is a class that handles complex numbers, and although an exception occurs in 0x8
, strings containing ʻi` may be bypassed.
Is it painful to use to_i
for standard output, or I think it's better to use regular expressions as usual.
Referenced site
Recommended Posts