Ruby 异常处理与正则表达式

发布: (2025年12月31日 GMT+8 12:42)
3 min read
原文: Dev.to

Source: Dev.to

异常处理

在 Ruby 中查看触发和处理异常的基本方法。

def raise_exception
  puts 'I am before the raise.'
  raise 'An error has occured'
  puts 'I am after the raise'  # 실행되지 않음
end

raise_exception

上面的示例展示了使用 raise 触发异常后,异常发生点之后的代码不会被执行。

def raise_and_rescue
  begin
    puts 'I am before the raise.'
    raise 'An error has occured.'
    puts 'I am after the raise.'
  rescue
    puts 'I am rescued.'
  end
  puts 'I am after the begin block.'
end

raise_and_rescue

使用 begin … rescue … end 语句时,如果出现异常会执行 rescue 块,随后代码会正常继续执行。

也可以区分不同的异常类型进行处理。

begin
  # ...
rescue OneTypeOfException
  # ...
rescue AnotherTypeOfException
  # ...
else
  # 다른 예외들
end

捕获异常对象并输出详细信息的方法:

begin
  raise 'A test exception.'
rescue Exception => e
  puts e.message          # 예외 메시지
  puts e.backtrace.inspect # 백트레이스
end

正则表达式

在 Ruby 中使用正则表达式匹配字符串并捕获内容的方法。

m1 = /Ruby/.match("The future is Ruby")
puts m1.class  # => MatchData

使用 =~ 运算符可以返回匹配的起始位置。

m2 = "The future is Ruby" =~ /Ruby/
puts m2        # => 14 (매칭 시작 위치)

捕获类似电话号码的模式示例:

string = "My phone number is (123) 555-1234."
phone_re = /\((\d{3})\)\s+(\d{3})-(\d{4})/
m = phone_re.match(string)

unless m
  puts "There was no match..."
  exit
end

print "The whole string we started with: "
puts m.string

print "The entire part of the string that matched: "
puts m[0]

puts "The three captures: "
3.times do |index|
  puts "Capture ##{index + 1}: #{m.captures[index]}"
end

puts "Here's another way to get at the first capture:"
print "Capture #1: "
puts m[1]

上述代码会输出完整匹配的字符串 (m[0]) 以及每个捕获组 (m[1], m[2], m[3])。

Back to Blog

相关文章

阅读更多 »

Ruby 块和 Lambda

Ruby 块(Block)是 Ruby 中一种将代码块与方法调用一起传递的方式。ruby def call_block puts 'Start of method' yield yield puts 'End of method' end call_block { puts 'In...