如何提取Ruby中的整数符号? [英] How to extract the sign of an integer in Ruby?

查看:127
本文介绍了如何提取Ruby中的整数符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个返回/打印整数符号的函数。到目前为止,我想出了这个:

  def extract_sign(整数)
整数> = 0? '+':' - '
end

是否有内置的Ruby方法这是一个简单的方法来做到这一点:


解决方案

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

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

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

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

x = 0
±+ - [x< => 0]#=> ±

x = 3
±+ - [x = 0]#=> +


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?

解决方案

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

这篇关于如何提取Ruby中的整数符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆