【问题标题】:Using Ruby symbols as options使用 Ruby 符号作为选项
【发布时间】:2013-09-06 09:23:19
【问题描述】:

我想知道如何使用 Ruby 符号(例如 :foo)作为函数中的选项(而不是作为选项哈希)。

例子:

round(28.53, :floor)
get_data(:age)

如何创建一个接受此类参数的函数?

【问题讨论】:

    标签: ruby symbols


    【解决方案1】:

    这在很大程度上取决于您希望如何处理多个选项,但这里有一个示例,基于您的round

    def round( number, *opts )
      if opts.include?( :convert )
        number = number.to_f
      end
    
      if opts.include?( :floor )
        return number.floor
      elsif opts.include?( :ceil )
        return number.ceil      
      else
        return number.round
      end
    end
    
    round( 7.3 )
    # => 7
    
    round( 7.3, :floor )
    # => 7
    
    round( 7.3, :ceil )
    # => 8
    
    round( '7.3', :ceil )
    # => NoMethodError: undefined method `ceil' for "7.3":String
    
    round( '7.3', :ceil, :convert )
    # => 8
    

    * 构造允许您在最后接受一个参数数组,您可以使用它来传递多个选项。如果它们是互斥的(例如人为示例中的某些选项就是这种情况),那可能没有意义,但是没有一种方法签名可以涵盖所有可能的用例。

    【讨论】:

      【解决方案2】:

      如果您不必处理可变数量的参数,它就像任何其他参数一样工作:

      def round(number, rounds)
        case rounds
        when :floor
          number.floor
        when :ceil
          number.ceil
        when :round
          number.round
        else
          raise ArgumentError, "unknown rounding mode: #{rounds.inspect}"
        end
      end
      
      round(28.53, :floor) #=> 28
      round(28.53, :ceil)  #=> 29
      round(28.53, :round) #=> 29
      round(28.53, :foo)   #=> ArgumentError: unknown rounding mode: :foo
      

      【讨论】:

      • 我会给定义一个默认值:round(number, rounds = :round)
      【解决方案3】:

      假设您想向您的方法发送多个选项。如果存在选项(在这种情况下让我们打印它),您想要做一些事情,否则什么也不做/不要打扰

      def meth( opt = {} )
        opt.keys.each { |o| puts opt[0]
      end
      
      # pass two options 
      meth(:name => 'Ruby', :floor => 23.5) #=> Ruby, 23.5
      
      #pass one option
      meth(:name => 'Rails') #=> Rails
      

      【讨论】:

        【解决方案4】:

        有问题吗?

        def puts_class param
          puts param.class
        end
        
        puts_class :asd
        
        =>
        Symbol
        

        实际上,符号从未被假定为 Ruby 方法中的选项。这是关于哈希的:

        some_method(1,2, param: :value, param2: value2) # curly braces omitted
        # equal to
        some_method(1,2, {param: value, param2: value2})
        

        【讨论】:

          猜你喜欢
          • 2012-12-22
          • 2012-07-11
          • 2012-01-01
          • 2014-10-29
          • 2015-01-28
          • 2022-01-08
          • 1970-01-01
          • 2013-03-08
          • 1970-01-01
          相关资源
          最近更新 更多