Building a hash in a conditional way

后端 未结 11 840
梦如初夏
梦如初夏 2021-02-01 01:29

I am using Ruby on Rails 3.0.10 and I would like to build an hash key\\value pairs in a conditional way. That is, I would like to add a key and its related value if a condition

11条回答
  •  清歌不尽
    2021-02-01 02:00

    Using fetch can be useful if you're populating a hash from optional attributes somewhere else. Look at this example:

    def create_watchable_data(attrs = {})
      return WatchableData.new({
        id:             attrs.fetch(:id, '/catalog/titles/breaking_bad_2_737'),
        titles:         attrs.fetch(:titles, ['737']),
        url:            attrs.fetch(:url, 'http://www.netflix.com/shows/breaking_bad/3423432'),
        year:           attrs.fetch(:year, '1993'),
        watchable_type: attrs.fetch(:watchable_type, 'Show'),
        season_title:   attrs.fetch(:season_title, 'Season 2'),
        show_title:     attrs.fetch(:id, 'Breaking Bad')
      })
    end
    

提交回复
热议问题