我正在解析Linkedin API,您可以请求各种字段及其值。有时用户具有字段的值,有时则不具有。
例如,如果用户没有输入电话号码,则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'] : ""
答案 0 :(得分:8)
@user.email = profile['emailAddress'] || ""
@user.phone_number = profile['phoneNumber'] || ""
@user.first_name = profile['firstName'] || ""
@user.last_name = profile['lastName'] || ""
答案 1 :(得分:3)
这很简单 - 设置哈希的默认值:
> 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']
=> ""