# 添加 1 + 1 #=> 2 # 减法 2 - 1 #=> 1 # 乘法 2 * 2 #=> 4 # 分配 10 / 5 #=> 2 17 / 5 #=> 3, not 3.4 17 / 5.0 #=> 3.4 # 指数 2 ** 2 #=> 4 3 ** 4 #=> 81 # 模数(求除法的余数) 8 % 2 #=> 0 (8 / 2 = 4; 没有剩余) 10 % 4 #=> 2 (10 / 4 = 2 余数为 2) a = 10 b = 20 a == b #=> false a != b #=> true a > b #=> false a < b #=> true a >= b #=> false a <= b #=> true
# 比较运算符 a <=> b #=> -1 c = 20 c <=> b #=> 0 c <=> a #=> 1 # 用于测试 case 语句的 when 子句中的相等性 (1...10) === 5 #=> true # 如果接收者和参数具有相同的类型和相等的值,则为真 1.eql?(1.0) #=> false c = a + b #=> 30 c += a #=> 40 c -= a #=> 30 c *= a #=> 300 c /= a #=> 30 c %= a #=> 3 c **= a #=> 59049
# Ruby 并行赋值 a = 10 b = 20 c = 30 a, b, c = 10, 20, 30 # Ruby 位运算符 a = 60 b = 13 # & 如果两个操作数中都存在,则二进制 AND 运算符将位复制到结果中。 a & b #=> 12 # | 如果二进制或运算符存在于任一操作数中,则复制一个位。 a | b #=> 61 # ^ 二元异或操作符如果在一个操作数中设置,则复制该位,但不能同时在两个操作数中设置。 a ^ b #=> 49 # ~ 二进制补码运算符是一元的,具有“翻转”位的效果。 ~a # << 二进制左移运算符。 左操作数的值被移动 # 左操作数指定的位数。 a << 2 # >> 二进制右移运算符。 左操作数的值被移动 # 右操作数指定的位数。 a >> 2
# Ruby 逻辑运算符 a and b #=> true. a or b #=> true. a && b #=> true. (a || b) #=> true. !(a && b) #=> false. not(a && b) #=> false. # Ruby 三元运算符 # ? : # 如果条件为真? 然后值 X :否则值 Y a == 10 ? puts 'Right' : puts 'Wrong' # Ruby 范围运算符 # .. 创建从起点到终点的范围(含) 1..10 #=> 创建从 1 到 10 的范围(包括 1 到 10) # ... 创建一个从起点到终点的范围,不包括在内 1...10 #=> 创建一个从 1 到 10 的独占范围
temp = 19 if temp >= 25 puts "hot" elsif temp < 25 && temp >= 18 puts "normal" else puts "cold" end # 输出 => normal
除非语句
1 2 3 4 5 6 7 8 9 10 11 12
# 除非与 if 相反,当语句为假时进行评估 name = "rob" # if name != "bob" unless name == "bob" puts "hello stranger" else puts "hello bob" end # 输出 => hello stranger num = 6 puts 'not two'unless num == 2 # 输出 => not two
# case 返回最后执行的表达式的值 case input # 检查一个整数,19 when19 puts "It's 19" # 检查浮点数,33.3 when33.3 puts "It's 33.3" # 检查一个确切的字符串,“Zaman” when"Zaman" puts "Hi Zaman" when10 puts "It's 10" # 检查范围 when7..11 puts "It's between 7 and 11" # 检查多个值,“咖啡” when"tea", "coffee" puts "Happy days" # 检查正则表达式“aA6” when /^a[A-Z]+[0-6]+$/ puts "It's a valid match" # 通过与 String 类“任何字符串” # 进行比较来检查任何字符串 when String puts "It's a String" end
case 简短的语法
1 2 3
case input when19then puts "It's 19" end
case 可选的失败
1 2 3 4 5
case input when19then puts "It's 19" else puts "It's not 19" end
case 获取返回值
1 2 3 4 5 6 7 8 9 10 11 12
marks = 86 result = case marks when0..49then"Fail" when50..64then"Pass" when65..74then"Credit" when75..84then"Distinction" when85..100then"High Distinction" else"Invalid marks" end
puts result # High Distinction
字符串
字符串插值
1 2 3 4
name = "World" puts "Hello #{name}" puts "The total is #{1+1}" # "the total is 2"
Mobile = Class.new do defself.ring "ring ring ring..." end end Mobile.ring
1 2 3 4 5 6 7
Mobile = Class.new class << Mobile defring "ring ring ring..." end end Mobile.ring
使用另一个参数作为默认值
1 2 3 4 5
defmethod_name(num1, num2 = num1) return num1 + num2 end res = method_name(10) # 输出 => 20
为方法参数定义默认值
1 2 3 4 5 6 7
defmethod_name(parameter1, parameter2, type = "ADD") puts "#{parameter1}#{parameter2}" return parameter1 + parameter2 if type == "ADD" return parameter1 - parameter2 if type == "SUB" end res = method_name(20, 10) # 输出 => 30
将可变长度参数传递给方法参数
1 2 3 4 5 6 7 8 9 10 11 12
defmethod_name(type, *values) return values.reduce(:+) if type == "ADD" return values.reduce(:-) if type == "SUB" end numbers = [2, 2, 2, 3, 3, 3] res = method_name("ADD", *numbers) # 输出 => 15 res = method_name("SUB", *numbers) # 输出 => -11 # 或者您可以提供这样的值 res = method_name("ADD", 2, 2, 2, 3, 3, 3) # 输出 => 15
defgive_me_data puts "我在 give_me_data 方法里面" p = Proc.new { return10 } p.call # 代码从这里返回 puts "I am back in give_me_data method" end
return_value = give_me_data puts return_value
# 输出 # 我在 give_me_data 方法里面 # 10
Lambdas
声明一个 lambda
1 2 3 4 5 6
l = lambda { puts "Hello World" } # 速记 l = -> { puts "Hello World" } # 调用 lambda l.call # 输出 => Hello World
有多种方法可以调用 lambda
1 2
l.() l[]
严格的 arguments
1 2 3 4 5 6 7
l = -> (count) { "Hello World " * count } l.call 5 # 输出 # "Hello World Hello World Hello World Hello World Hello World " l.call 5, 2 # 输出 wrong number of arguments (given 2, expected 1)
块中声明一个 lambda
1 2 3 4 5 6 7 8 9 10 11 12 13 14
defgive_me_data puts "I am inside give_me_data method" l = -> { return10 } l.call puts "I am back in give_me_data method" end
return_value = give_me_data puts return_value
# 输出 # I am inside give_me_data method # I am back in give_me_data method # nil # because puts return nil
# numbers[start..end], both index are inclusive puts numbers[0..3] # 1 # 2 # 3 # 4 # numbers[start..end], end index is exclusive puts numbers[0...3] # 1 # 2 # 3 # or numbers[start..length] puts numbers[0, 1] # 1
获取数组的前n个元素
1 2 3
primes = [7, 2, 3, 5] primes.take(3) # [7, 2, 3]
访问元素
1 2 3 4 5 6 7 8 9
primes = [7, 2, 3, 5] primes.fetch(3) # 5 # Fetch will throw an error if the element does not exist primes.fetch(10) # (index 10 outside of array bounds: -4...4) # or get an default value primes.fetch(10, -1) # -1
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] index = 0 while index < planets.size puts "#{planets[index]}" index += 1 end
1 2 3 4 5 6 7
a = 1 star = '*' while a <= 10 puts star star += '*' a += 1 end
do while
1 2 3 4 5 6 7
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] index = 0 loop do puts "#{planets[index]}" index += 1 breakif planets[index] == "Mars"or index > planets.size end
until
1 2 3 4 5 6
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] index = planets.size - 1 until index < 0 puts "#{planets[index]}" index -= 1 end
1 2 3 4 5 6 7
a = 1 star = '*' until star.length > 10 puts star star += '*' a += 1 end
words = %w[first second third fourth fifth sixth] str = "" words.reverse_each {|word| str += "#{word} "} p str #=> "sixth fifth fourth third second first "
# variable count count = 4 # using while loop # here conditional is count i.e. 4 while count >= 1 # statements to be executed puts "Ruby Cheatsheet" count = count - 1 # while loop ends here end
# starting of do..while loop loop do puts "Ruby Cheatsheet" val = '7' # using boolean expressions if val == '7' break end # ending of ruby do..while loop end
输出
1
Ruby Cheatsheet
until 循环
1 2 3 4 5 6 7 8
var = 7 # here do is optional until var == 11do # code to be executed puts var * 10 var = var + 1 # here loop ends end
输出
1 2 3 4
70 80 90 100
跳出循环
1 2 3 4 5 6 7 8
salary = [399, 234, 566, 533, 233] salary.each do |s| breakif s == 566 puts s end # 输出 # 399 # 234
通过使用 break 关键字
在循环内跳过
1 2 3 4 5 6 7 8 9 10
salary = [399, 234, 566, 533, 233] salary.each do |s| nextif s == 533 puts s end # 输出 # 399 # 234 # 566 # 233
data = [456, 3000] retry_count = 0 status = "network failure" sum = 0 data.each do |d| if retry_count == 3 status = "connection established" retry_count = 0 redo elsif status == "network failure"and retry_count < 5 puts "network failure #{retry_count}" retry_count += 1 redo elsif status == "connection established" puts d sum += d end end # output of sum # 3456
重新开始循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
numbers = [2, 2, 44, 44] sum = 0 begin numbers.each do |s| if rand(1..10) == 5 puts "hi 5, let's do it again!" sum = 0 raise "hi 5" end puts s sum += s end rescue retry end
classPerson # when you create a new object, it looks for a method named initialize and executes it, like a constructor in java # def initialize(name, number) # @name = name # @number = number # end # instance variable # @name # class variable # @@count # attr_accessor acts as a getter and setter for the following instance attributes attr_accessor:name, :number # class variable must be initialized @@count = 0 defself.count @@count end defself.count=(count) @@count = count end definitialize @@count += 1 end end # create an instance of the Person class p1 = Person.new # set attributes of the Person class p1.name = "Yukihiro Matsumoto" p1.number = 9999999999 # get attributes of the Person class puts "#{p1.name}" puts "#{p1.number}" puts "#{Person.count}" # Yukihiro Matsumoto # 9999999999 # 1 p2 = Person.new p2.name = "Yukihiro Matsumoto" p2.number = 9999999999 # get attributes of the Person class puts "#{p2.name}" puts "#{p2.number}" puts "#{Person.count}" # Yukihiro Matsumoto # 9999999999 # 2 # set class variable Person.count = 3 puts "#{Person.count}" # 3
继承一个类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classPerson attr_accessor:name, :number end # 使用 < 符号从父类继承方法和属性 classStudent < Person attr_accessor:id end s = Student.new s.name = "James Bond" s.number = 700 s.id = 678 puts "#{p.name}" James Bond puts "#{p.number}" 700 puts "#{p.id}" 678
检查实例类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classVehicle; end classCar < Vehicle; end classAudi < Car; end car = Car.new car.instance_of? Vehicle false car.instance_of? Car true car.instance_of? Audi false a = 7 a.instance_of? Integer true a.instance_of? Numeric false