Ruby 和 Python 语法对应参照列表

为了读一本用 Ruby 描述的书,而又不想专门学习 Ruby 的语法,故有了这部分内容整理。

Ruby Python 说明
# # 单行注释
=begin=end """""" 多行注释
puts print 输出到标准输出
gets input 从标准输入获取字符串
a = 1 a = 1 变量赋值
a.class type(a) 获取变量的类型
"hello" + "world" "hello" + "world" 字符串拼接
"hello" * 3 "hello" * 3 字符串重复
"hello"[0] "hello"[0] 字符串索引
"hello"[0..2] "hello"[0:3] 字符串切片
"hello".length len("hello") 字符串长度
"hello".reverse "hello"[::-1] 字符串反转
"hello".upcase "hello".upper() 字符串转大写
"HELLO".downcase "HELLO".lower() 字符串转小写
"hello".capitalize "hello".capitalize() 字符串首字母大写
"hello".include?("ll") "ll" in "hello" 判断字符串是否包含子串
[1, 2, 3] [1, 2, 3] 列表(数组)字面量
[1, 2, 3].length len([1, 2, 3]) 列表(数组)长度
[1, 2, 3][0] [1, 2, 3][0] 列表(数组)索引
[1, 2, 3][0..1] [1, 2, 3][0:2] 列表(数组)切片
[1, 2, 3].push(4) or [1, 2, 3] << 4 [1, 2, 3].append(4) or [1, 2, 3] + [4] 列表(数组)添加元素
[1 ,2 ,3][0] and [1 ,2 ,3][0]=nil or [1 ,2 ,3].slice!(0) or [1 ,2 ,3].unshift(4) or [4]+[1 ,2 ,3].pop() or [4]+[1 ,2 ,3].delete_at(-1) or [4]+[1 ,2 ,3][-1] and [4]+[1 ,2 ,3][-1]=nil.pop() or [4]+[1 ,2 ,3].slice!(-1).pop() or [4]+[1 ,2 ,3].shift().pop() or [4]+[1 ,2 ,3].delete_at(0).pop() or [4]+[1 ,2 ,3][0] and [4]+[1 ,2 ,3][0]=nil.pop()` [1, 2, 3].pop() or del [1, 2, 3][-1] 列表(数组)删除最后一个元素
[1, 2, 3].shift() or [1, 2, 3].delete_at(0) or [1, 2, 3][0] and [1, 2, 3][0]=nil or [1, 2, 3].slice!(0) [1, 2, 3].pop(0) or del [1, 2, 3][0] 列表(数组)删除第一个元素
[1, 2, 3].unshift(4) or [4]+[1, 2, 3] [1, 2, 3].insert(0, 4) or [4] + [1, 2, 3] 列表(数组)在开头插入元素
[1, 2, 3].insert(1, 4) [1, 2, 3].insert(1, 4) 列表(数组)在指定位置插入元素
a = [1, 2]; b = a; b[0] = -1; a a = [1, 2]; b = a; b[0] = -1; a 列表(数组)赋值是引用传递
a = [1, 2]; b = a.dup; b[0] = -1; a a = [1, 2]; b = a.copy(); b[0] = -1; a 列表(数组)赋值是值传递
a = [5]; b = a * -5; b a = [5]; b = a * -5; b 列表(数组)乘以负数为空列表(数组)
{a: "apple", b: "banana"} or {:a => "apple", :b => "banana"} {"a": "apple", "b": "banana"} 字典(哈希)字面量
{a: "apple", b: "banana"}[:a] or {:a => "apple", :b => "banana"}[:a] {"a": "apple", "b": "banana"}["a"] 字典(哈希)索引
{a: "apple", b: "banana"}.keys or {:a => "apple", :b => "banana"}.keys {"a": "apple", "b": "banana"}.keys() 字典(哈希)获取所有的键
{a: "apple", b: "banana"}.values or {:a => "apple", :b => "banana"}.values {"a": "apple", "b": "banana"}.values() 字典(哈希)获取所有的值
{a: "apple", b: "banana"}.length or {:a => "apple", :b => "banana"}.length len({"a": "apple", "b": "banana"}) 字典(哈希)的长度
{a: "apple", b: "banana"}.merge({c: "cherry"}) or {:a => "apple", :b => "banana"}.merge({:c => "cherry"}) {"a": "apple", "b": "banana"}.update({"c": "cherry"}) 字典(哈希)合并
{a: "apple", b: "banana"}.delete(:a) or {:a => "apple", :b => "banana"}.delete(:a) del {"a": "apple", "b": "banana"}["a"] 字典(哈希)删除键值对
true True 布尔值真
false False 布尔值假
nil None 空值
!true or not true not True 布尔值取反
true and false or true && false True and False 布尔值与运算
true or false or `true false`
(1..10) or (1...11) range(1, 11) 范围(区间)字面量
(1..10).to_a or (1...11).to_a list(range(1, 11)) 范围(区间)转换为列表(数组)
(1..10).include?(5) or (1...11).include?(5) 5 in range(1, 11) 判断范围(区间)是否包含某个元素
(1..10).each { |x| puts x } or (1...11).each { |x| puts x } for x in range(1, 11): print(x) 遍历范围(区间)中的元素
(1..10).map { |x| x * 2 } or (1...11).map { |x| x * 2 } [x * 2 for x in range(1, 11)] 对范围(区间)中的元素进行映射操作
(1..10).select { |x| x.even? } or (1...11).select { |x| x.even? } [x for x in range(1, 11) if x % 2 == 0] 对范围(区间)中的元素进行筛选操作
if x > 0 then puts "positive" elsif x < 0 then puts "negative" else puts "zero" end if x > 0: print("positive") elif x < 0: print("negative") else: print("zero") 条件语句
case x when 1 then puts "one" when 2 then puts "two" else puts "other" end if x == 1: print("one") elif x == 2: print("two") else: print("other") 分支语句
while x > 0 do puts x; x -= 1 end while x > 0: print(x); x -= 1 循环语句
for i in (1..10) do puts i end or (1..10).each do |i| puts i end for i in range(1, 11): print(i) 遍历语句
break break 跳出循环
next continue 跳过本次循环
return x or x return x 返回值
def add(x, y) return x + y end or def add(x, y) x + y end def add(x, y): return x + y 定义函数
add(1, 2) or add 1, 2 add(1, 2) 调用函数
def add(x, y = 0) return x + y end or def add(x, y = 0) x + y end def add(x, y = 0): return x + y 定义带有默认参数的函数
add(1) or add(1, 2) or add 1 or add 1, 2 add(1) or add(1, 2) 调用带有默认参数的函数
def add(*args) return args.sum end or def add(*args) args.sum end def add(*args): return sum(args) 定义带有可变参数的函数
add(1, 2, 3) or add 1, 2, 3 add(1, 2, 3) 调用带有可变参数的函数
def add(x:, y:) return x + y end or def add(x:, y:) x + y end def add(**kwargs): return kwargs["x"] + kwargs["y"] 定义带有关键字参数的函数
add(x: 1, y: 2) or add x: 1, y: 2 add(x = 1, y = 2) 调用带有关键字参数的函数
lambda { |x| x * 2 } or ->(x) { x * 2 } lambda x: x * 2 匿名函数(lambda)字面量
(lambda { |x| x * 2 }).call(5) or (->(x) { x * 2 }).call(5) (lambda x: x * 2)(5) 调用匿名函数(lambda)
[1, 2, 3].map(&lambda { |x| x * 2 }) or [1, 2, 3].map(&->(x) { x * 2 }) list(map(lambda x: x * 2, [1, 2, 3])) 使用匿名函数(lambda)作为参数
[1, 2, 3].select(&lambda { |x| x.even? }) or [1, 2, 3].select(&->(x) { x.even? }) list(filter(lambda x: x % 2 == 0, [1, 2, 3])) 使用匿名函数(lambda)作为参数
class Person attr_accessor :name def initialize(name) @name = name end def say_hello puts "Hello, #{@name}!" end end class Person: def __init__(self, name): self.name = name def say_hello(self): print(f"Hello, {self.name}!") 定义类
p = Person.new("Alice") p = Person("Alice") 创建类的实例
p.name p.name 访问类的属性
p.name = "Bob" p.name = "Bob" 修改类的属性
p.say_hello p.say_hello() 调用类的方法
class Student < Person attr_accessor :grade def initialize(name, grade) super(name) @grade = grade end def say_hello puts "Hello, #{@name}! I'm in grade #{@grade}." end end class Student(Person): def __init__(self, name, grade): super().__init__(name) self.grade = grade def say_hello(self): print(f"Hello, {self.name}! I'm in grade {self.grade}.") 定义子类
s = Student.new("Charlie", 5) s = Student("Charlie", 5) 创建子类的实例
s.name s.name 访问子类的属性
s.grade s.grade 访问子类的属性
s.say_hello s.say_hello() 调用子类的方法
module Math def self.square(x) x * x end end def square(x): return x * x 定义模块
Math.square(2) square(2) 调用模块的方法
require "math" import math 导入模块
Math.sqrt(2) math.sqrt(2) 调用模块的方法
require "math" or include Math from math import * 导入模块的所有方法
sqrt(2) sqrt(2) 调用模块的方法
a = [1, 2, 3] a = [1, 2, 3] 定义数组(列表)
a[0] a[0] 访问数组(列表)的元素
a[0] = 4 a[0] = 4 修改数组(列表)的元素
a.length len(a) 获取数组(列表)的长度
a << 5 or a.push(5) a.append(5) 向数组(列表)的末尾添加元素
a.pop a.pop() 从数组(列表)的末尾删除元素
a.unshift(0) a.insert(0, 0) 向数组(列表)的开头添加元素
a.shift a.pop(0) 从数组(列表)的开头删除元素
a + [6, 7] a + [6, 7] 连接两个数组(列表)
[1, 2, 3] * 2 or [1, 2, 3].cycle(2).to_a [1, 2, 3] * 2 or [x for x in [1, 2, 3] for _ in range(2)] 复制数组(列表)的元素

猜你喜欢

转载自blog.csdn.net/SmileBasic/article/details/130965186