A simple comparison of Python and Ruby syntax

Source: Internet
Author: User
Tags instance method

Enter the interactive interpreter

python

Irb/pry


Set Encoding#coding =utf-8
#coding: Utf-8

Package ManagementEasy_install/pip Gem
Pip Install Markdown

Gem Install Markdown

NotesPython line Comment # starts
Python Multiline comments use three single quotation marks ("') or three single quotation marks (" ").
‘‘‘
Multi-line Comment 1
Multi-line Comment 2

‘‘‘


Ruby Line comment starts with #
Ruby Multi-line annotations use =begin =end
=begin
Multi-line Comment 1
Multi-line Comment 2
=end

Data Typepython data types are: numbers, strings, lists, tuples, dictionaries, etc.
Ruby's data types are: numbers, strings, arrays, hash tables, intervals, symbols, etc.

Ruby's Range
.. Closed intervals, including values at the right end
... Semi-closed interval, excluding the value at the right end

String

can be in single or double quotes, s = ' hello,dear!!! '


Python
Left-to-right index starts at default 0, with a maximum range of 1 less string lengths
Right-to-left index starts with default-1, the maximum range is the beginning of the string
Get string s[header subscript: tail subscript] does not contain tail subscript element

Ruby
Get string s[header, length]
Gets the string s[header subscript: Tail subscript] contains the tail subscript element; s[Head subscript ... Tail subscript] does not contain tail subscript element

Array
can be used [],array = [1,2,3,4]


Python Get child list
Array[0] First element
Array[1:] All elements of the second to the end
Array[1:3] Second to third element (second to fourth element, excluding fourth)


Ruby Get Child list
Array[0] First element
Array[1..-1] The second to the end of all elements
ARRAY[1..3] Second to fourth element (second to fourth element, including fourth)
ARRAY[1...3] Second to third element (second to fourth element, excluding fourth)

Python tuples
Tuples are similar to lists (list), with a "()" identifier, and inner elements separated by commas. However, an element cannot be assigned two times, which is equivalent to a read-only list
tuple = (1,2,3,4)


Hash
Python
DIC = {"K1": "V1", "K2": "V2"}
dic["K1"]

Ruby
DIC = {"K1" = ' v1 ', ' k2 ' = ' v2 '}
DIC = {: K1 = ' v1 ',: K2 = ' v2 '}
DIC = {k1: ' v1 ', K2: ' V2 '}
dic["K1"]
DIC[:K1]

Conditional JudgmentPython program language specifies 0, NULL, FALSE for False
Ruby Program language specifies nil, false is False


Python
If condition:
Code:
Elif codition:
Code:
else:
Code:


Ruby
If/unless condition [Then]
Code:
elsif condition [Then]
Code:
Else
Code:
End


Simple statement
Python
If Codition:code
Ruby
Code if condition

LoopsPython
While condition:
Code:
else:
Code:

For Var in sequ:
Code:
else:
Code:

Ruby
While Conditin [do]
Code
End


for Var in sequ [do]
Code
End

functionPython
The function code block begins with a def keyword followed by the function identifier name and parentheses ().
Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
The first line of the function statement can optionally use the document string-for storing the function description.
The function contents begin with a colon and are indented.
RETURN[EXP] End Function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.


All parameters (independent variables) are passed by reference in Python. If you modify the parameters in the function, the original parameters are changed in the function that called the function.
def say (Sth,age = 10,*var_params):
' Function Description Document '
Code
return [EXP]


anonymous functions
Python uses lambda to create anonymous functions.
Lambda is just an expression, and the function body is much simpler than def.
The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.
Lambda [arg1 [, Arg2,..... argn]]:expression


Ruby
Each method in Ruby returns a value by default, and the value returned is the value of the last statement.
def say (sth,age = 10,*var_params)
Code
End


Block
In Ruby, the code between {} or Do...end is a block of code.
Code blocks can only appear behind a method, which is immediately on the same line as the last parameter of the method, and is typically called by the yield keyword to code in the code block.


ModulePython
Modules allow you to logically organize your Python code snippets.
Assigning the relevant code to a module will make your code better and easier to understand.
The module is also a Python object, with a random name attribute used to bind or reference.
Simply put, the module is a file that holds the Python code. Modules can define functions, classes, and variables. Executable code can also be included in the module

Ruby
Module is a way of combining methods, classes, and constants. Module provides two great benefits for you.
The module provides a namespace and avoids name collisions.
The module realizes the Mixin device.
Module defines a namespace equivalent to a sandbox in which your methods and constants do not conflict with method constants elsewhere.

classpython
If a Python function, the class method, or the name of the property starts with two underscores (but not the end), it is private; all else is public.

Class method
Python2.2 You can use the @classmethod adorner to create a class method later. Its first argument is the class, and the contract is written as a CLS

Instance method
When defining your own method, you must list self as the first parameter of each method, including __init__.


There are no constants in Python


Class Vector:

Class_var = 0# class variable

def __init__ (self,a,b):

' Constructors '
Self.instance_var = a #实例变量
Code

def __del__ (self):
' destructor '
Code

@classmethod
Def say (CLS):
Code:

Inherited
Python
Support Multiple inheritance
Class A:
...
Class B:
...
Class C (A, B):
...


Ruby
Everything in Ruby is an object, including a constant.
For example, you can use the. Class property to see the type of an object, you can see the 1.class, you will find that the type of constant 1 is fixnum,1 is just an instance of Fixnum.


Classes in Ruby begin with a class with end, and the first letter of the class name is capitalized.
The method in Ruby begins with the Def and ends with end, and the first letter of the method name is lowercase.
The first letter of the local variable name in Ruby is a lowercase contract.
The constructor name in Ruby is initialize.
A member variable (instance variable) in Ruby has a leading @ character, which is declared and initialized in initialize.
Attributes in Ruby are used by attr, Attr_reader, Attr_writer, Attr_accessor.
The global variable in Ruby has leading $ characters.
Constants (constants) in Ruby begin with uppercase letters, with all uppercase conventions.


Initalize method


When Ruby creates a new object, it always looks for a method named Initialize and executes it. Therefore, we can simply add a default value to a real variable by using a Initialize method.


Class Person


Def initialize ()
Puts "hello! "
End


# def Initialize # () omit the same
#Puts "hello!"
# End


#参数默认值
# def initialize (param = "1900lab") # parameter with default value
#Puts "hello!" + param
# End


#可变长参数
def youinput (*names)
Puts "input #{names.join (", ")}!"
End
End


p = person.new ()
As with P = person.new, no parameters () can be omitted.


Property
The goal is to quickly generate read and write methods


ATTR:ATTR1, key
ATTR_READER:ATTR1,: ATTR2
ATTR_WRITER:ATTR1,: ATTR2
ATTR_ACCESSOR:ATTR1,: ATTR2


Attr typically followed by a symbolic parameter, the second parameter is a bool parameter that indicates whether a write method is generated for the symbol parameter. Its default value is False, only the Read method is generated, and no write method is generated.
Attr_reader typically followed by a symbol parameter, which defines one or more read-only properties that indicate the generation of read methods for symbolic parameters.
Attr_writer typically followed by a symbol parameter, which defines one or more write-only properties that indicate the generation of a write method for the symbolic parameter.
Attr_accessor typically followed by a symbol parameter, which defines one or more read-write properties that indicate the generation of read and write methods for symbolic parameters.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

A simple comparison of Python and Ruby syntax

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.