有条件地设置哈希键的值

时间:2015-04-30 07:08:54

标签: ruby hash

我有一个方法可以返回已解析值的哈希值。如果满足条件,哈希中的某些值我想成为nil,但我无法在值中写入条件。

有没有办法可以有条件地设置密钥的值,而不会在哈希之外放置一堆if / else语句?

请参阅下面的asignee_handle:issue_closed_at:

def parse(issue)
    {
      github_id:          issue['id'].to_i,
      github_number:      issue['number'].to_i,
      github_url:         issue['url'],
      title:              issue['title'],
      body:               issue['body'],
      creator_handle:     issue['user']['login'],
      asignee_handle:     issue['assignee']['login'] if issue['assignee'] #can't do this,
      asignee_avatar_url: issue['assignee']['avatar_url'],
      issue_created_at:   issue['created_at'].to_datetime,
      issue_updated_at:   issue['updated_at'].to_datetime,
      issue_closed_at:    issue['closed_at'].to_datetime if issue['closed_at'],
      repo:               issue['url'].split('/')[5]
    }
  end

1 个答案:

答案 0 :(得分:1)

您可以使用val = "11:66:11" try: val = map(int, val.split(':')) except ValueError: return False if len(val) == 1: return val if len(val) == 2: if val[1] > 59: print "Bad seconds" return False if len(val) == 3: if val[2] > 59 or val[1] >59: print "Bad seconds / minutes" return False while len(val) < 3: split.insert(0,0) return = timedelta(hours=split[0],minutes=split[1],seconds=split[2]) 语句尝试以下条件分配:

if

或使用三元运算符asignee_handle: if issue['assignee'] then issue['assignee']['login'] end

[expression] ? [true] : [false]