1

我现在正在解析 Linkedin API,您可以请求各种字段及其值。有时用户有一个字段的值,有时他们没有。

例如,如果用户没有输入电话号码,Linkedin 将不会返回电话号码字段。

对 Linkedin 的示例请求

email, firstName, lastName, phoneNumber

来自Linkedin的示例响应:

{"email"=>"test@example.com", "firstName"=>"Brian", "lastName"=>"Weinreich"}

所以,我要求 4 件事:email, firstName, lastName, phoneNumber它只返回 3 件事。我想知道是否有更快/更有效的方法来设置等于这些值的变量,具体取决于它们是否存在。

我就是这样做的……但这似乎是多余的。

@user.email = profile['emailAddress'] ? profile['emailAddress'] : ""
@user.phone_number = profile['phoneNumber'] ? profile['phoneNumber'] : ""
@user.first_name = profile['firstName'] ? profile['firstName'] : ""
@user.last_name = profile['lastName'] ? profile['lastName'] : ""
4

2 回答 2

8
@user.email = profile['emailAddress'] || ""
@user.phone_number = profile['phoneNumber'] || ""
@user.first_name = profile['firstName'] || ""
@user.last_name = profile['lastName'] || ""
于 2013-03-18T15:16:09.440 回答
3

这相当简单 - 为 Hash 设置默认值:

> profile={"email"=>"test@example.com", "firstName"=>"Brian", "lastName"=>"Weinreich"}
=> {"email"=>"test@example.com", "firstName"=>"Brian", "lastName"=>"Weinreich"}
> profile.default = ""
=> ""

那么只需简单的分配就可以满足您的要求:

@user.email = profile['emailAddress']
@user.phone_number = profile['phoneNumber']
@user.first_name = profile['firstName']
@user.last_name = profile['lastName']

Proc对于更复杂的情况,您还可以设置而不是一个默认值块:

profile.default_proc= proc {|hash, key| hash[key] = (key =~ /email/i) ? "default@example.com" : ""}

> profile['email']
=> "test@example.com"
> profile['hiddenEmail1234']
=> "default@example.com"
> profile['some-other-key']
=> ""
于 2013-03-18T16:23:01.977 回答