You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级至Ruby 3.1.3后twilio-ruby无法正常工作的问题求助

问题

使用Twilio API发送消息已有3年,此前运行完全正常。将Ruby从2.6版本升级至3.1.3版本后,Twilio功能失效。当前使用twilio-ruby 5.74.2版本,出现错误:ArgumentError (wrong number of arguments (given 1, expected 0))。

相关业务代码:

def send_pin_through_twilio
        client = Twilio::REST::Client.new
        client.messages.create({
            from: ENV["twilio_phone_number"],
            to: self.phone_number,
            body: "Hello from ...! Your one-time pin is #{self.one_time_pin}."
        })
end

错误日志:

2023-02-03T17:11:25.312087+00:00 app[web.2]: F, [2023-02-03T17:11:25.311995 #4] FATAL -- : [0d0b1732-1dbc-4170-a3d3-ba99bb7a676e]
2023-02-03T17:11:25.312089+00:00 app[web.2]: [0d0b1732-1dbc-4170-a3d3-ba99bb7a676e] ArgumentError (wrong number of arguments (given 1, expected 0)):
2023-02-03T17:11:25.312089+00:00 app[web.2]: [0d0b1732-1dbc-4170-a3d3-ba99bb7a676e]
2023-02-03T17:11:25.312090+00:00 app[web.2]: [0d0b1732-1dbc-4170-a3d3-ba99bb7a676e] app/models/user.rb:157:in `send_pin_through_twilio'
2023-02-03T17:11:25.312090+00:00 app[web.2]: [0d0b1732-1dbc-4170-a3d3-ba99bb7a676e] app/controllers/api/v3/users_controller.rb:127:in `login_next'
2023-02-03T17:11:25.320370+00:00 heroku[router]: at=info method=PUT path="/api/v3/users/login_next" host=app.hiwave.co request_id=0d0b1732-1dbc-4170-a3d3-ba99bb7a676e fwd="73.179.143.247,108.162.212.48" dyno=web.2 connect=0ms service=2790ms status=500 bytes=307 protocol=https

Twilio初始化代码:

Twilio.configure do |config|
  config.account_sid = ENV["accountsid"]
  config.auth_token = ENV["authtoken"]
end

解决方案

方法1:升级twilio-ruby版本

旧版本的twilio-ruby(5.74.2)对Ruby 3.x的关键字参数兼容性不足,升级到5.75.0及以上版本即可修复该问题,新版本已适配Ruby 3的参数处理规则。

方法2:修改调用方式(不升级gem)

如果暂时无法升级gem,需将传入create的哈希改为关键字参数传递,去掉外层大括号:

def send_pin_through_twilio
        client = Twilio::REST::Client.new
        client.messages.create(
            from: ENV["twilio_phone_number"],
            to: self.phone_number,
            body: "Hello from ...! Your one-time pin is #{self.one_time_pin}."
        )
end

或者显式使用双splat运算符将哈希转为关键字参数:

client.messages.create(**{
    from: ENV["twilio_phone_number"],
    to: self.phone_number,
    body: "Hello from ...! Your one-time pin is #{self.one_time_pin}."
})

问题根源

Ruby 3.0开始严格区分位置哈希参数和关键字参数,旧版本twilio-ruby在Ruby 2.6中可接受哈希作为关键字参数的替代,但Ruby 3.1会将该哈希视为单个位置参数传入,而create方法期望0个位置参数+若干关键字参数,因此触发参数数量错误。

内容的提问来源于stack exchange,提问作者Philip7899

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:10:40