Ruby 和 Python 语法对应参照列表

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

RubyPython说明
##单行注释
=begin=end""""""多行注释
putsprint输出到标准输出
getsinput从标准输入获取字符串
a = 1a = 1变量赋值
a.classtype(a)获取变量的类型
"hello" + "world""hello" + "world"字符串拼接
"hello" * 3"hello" * 3字符串重复
"hello"[0]"hello"[0]字符串索引
"hello"[0..2]"hello"[0:3]字符串切片
"hello".lengthlen("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].lengthlen([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; aa = [1, 2]; b = a; b[0] = -1; a列表(数组)赋值是引用传递
a = [1, 2]; b = a.dup; b[0] = -1; aa = [1, 2]; b = a.copy(); b[0] = -1; a列表(数组)赋值是值传递
a = [5]; b = a * -5; ba = [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"}.lengthlen({"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"]字典(哈希)删除键值对
trueTrue布尔值真
falseFalse布尔值假
nilNone空值
!true or not truenot True布尔值取反
true and false or true && falseTrue and False布尔值与运算
true or false or `truefalse`
(1..10) or (1...11)range(1, 11)范围(区间)字面量
(1..10).to_a or (1...11).to_alist(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" endif 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" endif x == 1: print("one") elif x == 2: print("two") else: print("other")分支语句
while x > 0 do puts x; x -= 1 endwhile x > 0: print(x); x -= 1循环语句
for i in (1..10) do puts i end or (1..10).each do |i| puts i endfor i in range(1, 11): print(i)遍历语句
breakbreak跳出循环
nextcontinue跳过本次循环
return x or xreturn x返回值
def add(x, y) return x + y end or def add(x, y) x + y enddef add(x, y): return x + y定义函数
add(1, 2) or add 1, 2add(1, 2)调用函数
def add(x, y = 0) return x + y end or def add(x, y = 0) x + y enddef add(x, y = 0): return x + y定义带有默认参数的函数
add(1) or add(1, 2) or add 1 or add 1, 2add(1) or add(1, 2)调用带有默认参数的函数
def add(*args) return args.sum end or def add(*args) args.sum enddef add(*args): return sum(args)定义带有可变参数的函数
add(1, 2, 3) or add 1, 2, 3add(1, 2, 3)调用带有可变参数的函数
def add(x:, y:) return x + y end or def add(x:, y:) x + y enddef add(**kwargs): return kwargs["x"] + kwargs["y"]定义带有关键字参数的函数
add(x: 1, y: 2) or add x: 1, y: 2add(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 endclass 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.namep.name访问类的属性
p.name = "Bob"p.name = "Bob"修改类的属性
p.say_hellop.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 endclass 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.names.name访问子类的属性
s.grades.grade访问子类的属性
s.say_hellos.say_hello()调用子类的方法
module Math def self.square(x) x * x end enddef square(x): return x * x定义模块
Math.square(2)square(2)调用模块的方法
require "math"import math导入模块
Math.sqrt(2)math.sqrt(2)调用模块的方法
require "math" or include Mathfrom math import *导入模块的所有方法
sqrt(2)sqrt(2)调用模块的方法
a = [1, 2, 3]a = [1, 2, 3]定义数组(列表)
a[0]a[0]访问数组(列表)的元素
a[0] = 4a[0] = 4修改数组(列表)的元素
a.lengthlen(a)获取数组(列表)的长度
a << 5 or a.push(5)a.append(5)向数组(列表)的末尾添加元素
a.popa.pop()从数组(列表)的末尾删除元素
a.unshift(0)a.insert(0, 0)向数组(列表)的开头添加元素
a.shifta.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)]复制数组(列表)的元素
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值