How to extract the sign of an integer in Ruby?

匿名 (未验证) 提交于 2019-12-03 02:18:01

问题:

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 

Is there a built-in Ruby method which does that?

回答1:

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] # => "+" 


回答2:

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. 


回答3:

You could use Kernel#sprintf to format numbers:

def sign(i)   sprintf("%+d", i)[0] end  sign(100)  #=> "+" sign(-100) #=> "-" 


回答4:

class Numeric   def sign     if self > 0       '+'     elsif zero?       nil     else       '-'     end   end end 


回答5:

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.



回答6:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!