gpt4 book ai didi

ruby - 是否有等效于 Rails `try` 函数的 Elixir?

转载 作者:数据小太阳 更新时间:2023-10-29 06:53:47 24 4
gpt4 key购买 nike

在 Rails 中,您可以执行以下操作:

@user.try(:contact_info).try(:phone_number)

如果 @usercontact_info 都不为 nil,则返回 phone_number。如果其中之一为 nil,则表达式将返回 nil。

我想知道在 Elixir 中最惯用的方法是什么,因为 @usercontact_info结构

最佳答案

我认为一种方法是使用模式匹配,所以它会是这样的:

case user do
%{contact_info: %{phone_number: phone_number}} when phone_number != nil ->
#do something when the phone number is present
_ ->
#do something when the phone number is absent
end

关于ruby - 是否有等效于 Rails `try` 函数的 Elixir?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35979175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com