How to extract the sign of an integer in Ruby?

前端 未结 7 2105
渐次进展
渐次进展 2020-12-30 00:49

I need a function which returns/prints the sign on an integer. So far I came up with this:

def extract_sign(integer)
  integer >= 0 ? \'+\' : \'-\'
end


        
相关标签:
7条回答
  • I think that it's nonsense not to have a method that just gives -1 or +1. Even BASIC has such a function SGN(n). Why should we have to deal with Strings when it's numbers we want to work with. But's that's just MHO.

    def sgn(n)
      n <=> 0
    end.
    
    0 讨论(0)
  • 2020-12-30 01:13

    Ruby doesn't have a built in sign function like Javascript. Here's a thread that explains more http://www.ruby-forum.com/topic/141216

    Your approach looks correct.

    0 讨论(0)
  • 2020-12-30 01:21

    Here is a simple way to do it:

    x = -3
    "++-"[x <=> 0] # => "-"
    
    x = 0
    "++-"[x <=> 0] # => "+"
    
    x = 3
    "++-"[x <=> 0] # => "+"
    

    or

    x = -3
    "±+-"[x <=> 0] # => "-"
    
    x = 0
    "±+-"[x <=> 0] # => "±"
    
    x = 3
    "±+-"[x <=> 0] # => "+"
    
    0 讨论(0)
  • 2020-12-30 01:27

    I use n == 0 ? 1 : n.abs / n, e.g.:

    def sign(n)
      n == 0 ? 1 : n.abs / n
    end
    
    sign(10) # 1
    sign(0) # 1
    sign(-5) # -1
    
    0 讨论(0)
  • 2020-12-30 01:28

    You could use Kernel#sprintf to format numbers:

    def sign(i)
      sprintf("%+d", i)[0]
    end
    
    sign(100)  #=> "+"
    sign(-100) #=> "-"
    
    0 讨论(0)
  • 2020-12-30 01:34
    class Numeric
      def sign
        if self > 0
          '+'
        elsif zero?
          nil
        else
          '-'
        end
      end
    end
    
    0 讨论(0)
提交回复
热议问题