Python の内包表記と Ruby の each_with_object
この記事は勉強になりました。Python の内包表記で
def create_url_table(urls) return {url: get_title(url) for url in urls if 'google' not in url}
と書くのを、Ruby の each_with_object を使うと
def create_url_table(urls) urls.each_with_object({}) do |url, hash| hash[url] = get_title(url) unless url.match(/google/) end end
と書けると。なるほど、each_with_object ってこんな風に使うのか。
※追記(2018/11/24)
こんな風にも書ける。
def create_url_table(urls) urls.reject{|u| u.match(/google/)}.map {|u| [u, get_title(u)]}.to_h end