如何更加优雅地使用ruby的命名参数(关键字参数)(没有重复的代码)?

时间:2016-07-03 16:55:01

标签: ruby named-parameters

很多时候,当我在ruby中使用命名参数时,我最终得到了这样的真实案例: calculate_multiplier( year: year, plant_location: plant_location, number_of_doors: number_of_doors, manufacturer: manufacturer )(您获得模式,键和变量名称相同的许多键值对)。 我可以在不复制代码的情况下编写吗?就像是: calculate_multiplier( :year, :plant_location, :number_of_doors, :manufacturer )

我想到了一个解决方案:

    class Object
      def to_np( caller_binding, *array ) # to named parameters
        np = Hash.new
        array.each\
        {
          | var |
          value = eval( "#{var}", caller_binding )
          if( value.is_a?( Hash ) )
            np.merge!( value )
          else
            np[ var ] = value
          end
        }
        return np
      end
    end

    class C
      def m( a:, **o )
        # do something
      end

      def m_wrapper
        # based on some logic contained in this method, we'll get:
        a = 'A'
        o = { x: 'X', y: 'Y' }

        # not that elegant I would say
        # m( a: a, **o )

        m( to_np( binding, :o, :a ) )
      end
    end

    puts RUBY_DESCRIPTION

    require 'benchmark'

    number = 1000000
    Benchmark.bm( 4 ) do |bm|
      bm.report( 'm_wrapper' ) { number.times { C.new.m_wrapper  } }
      bm.report( 'm        ' ) { number.times { C.new.m( a: 'A', x: 'X', y: 'Y' ) } }
    end

但是输出结果显示我对美的热爱是一种效率惩罚:)

ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-linux]
           user     system      total        real
m_wrapper 17.140000   0.030000  17.170000 ( 17.149647)
m          1.230000   0.000000   1.230000 (  1.238346)

还有其他建议吗?谢谢!

0 个答案:

没有答案