ruby推送示例
Ruby中的数字方法 (Number methods in Ruby)
Ruby provides a variety of built-in methods you may use on numbers. The following is an incomplete list of integer and float methods.
Ruby提供了多种可用于数字的内置方法。 以下是整数和浮点方法的不完整列表。
甚至 : (Even:)
Use .even?
to check whether or not an integer is even. Returns a true
or false
boolean.
使用.even?
检查整数是否为偶数。 返回一个true
或false
布尔值 。
15.even? #=> false
4.even? #=> true
奇数 : (Odd:)
Use .odd?
to check whether or not an integer is odd. Returns a true
or false
boolean.
使用.odd?
检查整数是否为奇数。 返回一个true
或false
布尔值 。
15.odd? #=> true
4.odd? #=> false
Ceil : (Ceil:)
The .ceil
method rounds floats up to the nearest number. Returns an integer.
8.3.ceil #=> 9
6.7.ceil #=> 7
楼层 : (Floor:)
The .floor
method rounds floats down to the nearest number. Returns an integer.
8.3.floor #=> 8
6.7.floor #=> 6
下一个 : (Next:)
Use .next
to return the next consecutive integer.
使用.next
返回下一个连续的整数 。
15.next #=> 16
2.next #=> 3
-4.next #=> -3
Pred : (Pred:)
Use .pred
to return the previous consecutive integer.
使用.pred
返回前一个连续整数 。
15.pred #=> 14
2.pred #=> 1
(-4).pred #=> -5
到字符串 : (To String:)
Using .to_s
on a number (integer, floats, etc.) returns a string of that number.
在数字( 整数 , 浮点数等)上使用.to_s
返回该数字的字符串 。
15.to_s #=> "15"
3.4.to_s #=> "3.4"
最大的共同分母 : (Greatest Common Denominator:)
The .gcd
method provides the greatest common divisor (always positive) of two numbers. Returns an integer.
.gcd
方法提供两个数字的最大公约数(总是正数)。 返回一个整数 。
15.gcd(5) #=> 5
3.gcd(-7) #=> 1
回合 (Round:)
Use .round
to return a rounded integer or float.
1.round #=> 1
1.round(2) #=> 1.0
15.round(-1) #=> 20
时间 : (Times:)
Use .times
to iterate the given block int
times.
使用.times
迭代给定的块int
时间。
5.times do |i|
print i, " "
end
#=> 0 1 2 3 4
Ruby中的数学运算 (Math operations in Ruby)
In Ruby you can perform all standard math operations on numbers, including: addition +
, subtraction -
, multiplication *
, division /
, find remainders %
, and work with exponents **
.
在Ruby中,您可以对数字执行所有标准的数学运算,包括:加+
,减-
,乘*
,除/
,求余数%
以及使用指数**
。
加成: (Addition:)
Numbers can be added together using the +
operator.
可以使用+
运算符将数字加在一起。
15 + 25 #=> 40
减法: (Subtraction:)
Numbers can be subtracted from one another using the -
operator.
可以使用-
运算符将数字彼此相减。
25 - 15 #=> 10
乘法: (Multiplication:)
Numbers can be multiplied together using the *
operator.
可以使用*
运算符将数字相乘。
10 * 5 #=> 50
师: (Division:)
Numbers can be divided by one another using the /
operator.
可以使用/
运算符将数字彼此除。
10 / 5 #=> 2
剩余部分: (Remainders:)
Remainders can be found using the modulus %
operator.
余数可以使用模数%
运算符找到。
10 % 3 #=> 1 # because the remainder of 10/3 is 1
指数: (Exponents:)
Exponents can be calculated using the **
operator.
可以使用**
运算符计算指数。
2 ** 3 #=> 8 # because 2 to the third power, or 2 * 2 * 2 = 8
翻译自: https://www.freecodecamp.org/news/ruby-number-methods-integer-and-float-methods-with-examples/
ruby推送示例