class Hash class << self def ruby2_keywords_hash?(hash) !new(*[hash]).default.equal?(hash) end def ruby2_keywords_hash(hash) _ruby2_keywords_hash(**hash) end private def _ruby2_keywords_hash(*args) args.last end ruby2_keywords(:_ruby2_keywords_hash) if respond_to?(:ruby2_keywords, true) end end RUBY_VERSION # => "2.7.0" def passed_kw?(*args) Hash.ruby2_keywords_hash?(args.last) end ruby2_keywords(:passed_kw?) if respond_to?(:ruby2_keywords, true) passed_kw?({ a: 1 }) # => false passed_kw?(a: 1) # => true hash = { a: 1 } passed_kw?(hash) # => false passed_kw?(**hash) # => true kw = Hash.ruby2_keywords_hash(hash) passed_kw?(kw) # => true passed_kw?(**kw) # => true
説ææ¸ããã¨ãããã©ã ãã¶ããã©ãããã£ãã®ã§ã³ã¼ãã§æãåã£ã¦ã»ãããã§ãããRuby 2.7.0以éRuby 3ã«åãã¦ãã¼ã¯ã¼ãå¼æ°æ¸¡ãã®éäºæããã³ããªã³ã°ããããã«ruby2_keywords
ã使ã£ã¦ãã¼ã¯ã¼ãå¼æ°æ¸¡ããããhashãªãã¸ã§ã¯ãã«ãã©ã°ãä»ãããã¨ãã§ãããã¨ãããRuby 2.6以åã¨Ruby 2.7以éã®ä¸¡æ¹ãµãã¼ããããã©ã¤ãã©ãªã¡ã³ããã¯ãã®ãã©ã°ãä»ãã¦åããªããã°Ruby 3ã§ã¯ArgumentErrorã§ãåã¯ããæ»ãã§ããç¶æ
ã«ãªã£ã¦ãã¾ãã
ãã©ã°ãä»ãããã®ã¯ããã¨ãã¦Ruby 2.7.0ã§ã¯ãã®ãã©ã°ãä»ãã¦ãhashãªãã¸ã§ã¯ããªã®ããããããªãhashãªãã¸ã§ã¯ããªã®ã確ãããæ¹æ³ãå ¬å¼ã«ã¯æä¾ããã¦ãªãã¦ãã©ãã§å¼ã³åºãããã¨ãã«ãã©ã°ãä»ããå¿ è¦ããã£ã¦ãã¡ããã¨ãã©ã°ãä»ããã¾ã¾ãå±ãå ã®ã¡ã½ããã¾ã§ãã©ãçãã¦ãã®ãã®ãããã°ãæ»ã¬ã»ã©ããã©ãããã£ãã
ããã¯mameããã®ããã¯ãè¦ã¦ç¥ã£ãæ¹æ³ã§ãããã¯ãã©ã°ãä»ãã¦ãhashãªãã¸ã§ã¯ãããããããªããªãã¸ã§ã¯ããã§éãæ¯ãèããããå¦çãéããã¦ãã®çµæã観測ãããã¨ã§ã©ã£ã¡ã ã£ããã確ãããã¨ããæ¹æ³ã§ãã
ãã®ãã©ã°ãä»ãã¦ãhashãªãã¸ã§ã¯ãããããããªããªãã¸ã§ã¯ããã§éãæ¯ãèããããå¦çãRubyã®ä¸çããã¯ã»ã¨ãã©åå¨ããªãã®ã§ãæ®æ®µRubyã§ã³ã¼ããæ¸ãã¦ã常人ãèªåã§ã¯æ°ã¥ããããã£ã¦æ¹æ³ã§ãä¸é¨ã®ã¡ã½ãã(initialize
ã¨ãmethod_missing
ã¨ã)ãRubyã®ã³ã¼ãããç´æ¥å¼ã³åºãããããªãã¦Cã®ã³ã¼ãããéæ¥çã«å¼ã³åºãããã¨ãã«ãã©ã°ãä»ãã¦ãhashãªãã¸ã§ã¯ããdup
ããã®ã§ãdup
ãããã«ãã®ã¾ã¾ã®ãªãã¸ã§ã¯ã(object_id
)ã ã£ãããã©ã°ãä»ãã¦ãªãã£ãã£ã¦ãã¨ã§dup
ããã¦å¥ã®ãªãã¸ã§ã¯ãã観測ãããããã©ã°ãä»ãã¦ããªãã¸ã§ã¯ãã ã£ãã¨ããæã使ã£ã¦ãã¾ãã
ãããã試è¡é¯èª¤ãã¦ã¿ã¦Ruby 2.7.0ã®æç¹ã§ã¯newãéããªãã¨args lastã«kwargs flagãä»ãã¦ããã©ããRubyã®ä¸çããã¯ç¢ºããããããªãã¨ãããã¨ãåãã£ããã©ããã¯ãã¸ã§çããå ã«ç¥ã£ã¦ãªãã¨æ°ã¥ãããããªãç¡çã²ã¼ããã
— Ryuta Kamizono (@kamipo) January 19, 2020
åçãåãã£ãã®ã§æ¢åã®ã¡ã½ããã§ãã®ç¨éã«ä¸åº¦ããã¡ã½ãããæ¢ããçµæãHash.new
ã«hashã®ããã©ã«ãå¤ã¨ãã¦ãã©ã°ä»ããããããªãhashãªãã¸ã§ã¯ããsplat渡ããã¦Hash#default
ã§åãåºãã¦è¦³æ¸¬ããã¨ããæ¹æ³ãä¸çªã·ã³ãã«ã§ãããã¨ããã¨ããã«è³ãããã®æã使ã£ã¦Railsã§ããã¼ã¯ã¼ãå¼æ°å®å
¨åé¢ã¸ã®å¯¾å¿ãé²ãã¦ãã¾ãã
ãã®ãã©ã°ä»ããã©ãã確ãããæ¹æ³ãããã®ããªãã®ã常人ã§ã¯æãè³ããåé¡ã«ã©ã¤ãã©ãªã¡ã³ããã¯ç´é¢ããã¨æãã¾ãããRuby 2.7.1ã«ã¯ãã©ã°ä»ããã©ãã確ãããæ¹æ³ãå ¬å¼ã«ããã¯ãã¼ããããäºå®ãªã®ã§ãããã§è¦åãå¤ãæ¥ãå®å¿ã§ããã