Simple comparison of python and ruby syntax, pythonruby syntax

Source: Internet
Author: User

Simple comparison of python and ruby syntax, pythonruby syntax
Enter the interactive Interpreter



Set encoding # coding = UTF-8
# Coding: UTF-8

Package management easy_install/pip gem
Pip install Markdown

Gem install Markdown

Annotate python single line comment # start
Python multi-line comments use three single quotes (''') or three single quotes (""").
Multi-line comment 1
Multi-line comment 2


Ruby single-line comment starts #
Ruby multi-line annotation = begin = end
= Begin
Multi-line comment 1
Multi-line comment 2
= End

Python data types include numbers, strings, lists, tuples, and dictionaries.
Ruby data types include numbers, strings, arrays, hash tables, ranges, and symbols.

Ruby Interval
.. Closed range, including the right end value
... Semi-closed range, excluding the right end value


You can use single or double quotation marks, s = 'hello, dear !!! '

From left to right index starts from 0 by default, and the maximum range is 1 less String Length
From right to left index start from-1 by default. The maximum range is the start of the string.
Returns the string s [header Subscript: tail subscript] which does not contain the end subscript element.

Obtain the string s [header subscript, length]
Obtain the string s [header subscript... tail subscript] containing the end subscript element; s [header subscript... tail subscript] does not contain the end subscript Element

[], Array = [1, 2, 4]

Obtain the sublist using python
Array [0] first element
Array [1:] All elements from the second end to the end
Array [] second to third elements (elements between the second and fourth, excluding the fourth element)

Ruby get sub-list
Array [0] first element
Array [1 ..-1] All elements from the second end to the end
Array [1 .. 3] elements from the second to the fourth (elements between the second and fourth, including the fourth)
Array [1... 3] elements from the second to the third (elements between the second and fourth, excluding the fourth)

Python tuples
Tuples are similar to lists and are identified by commas (,). Internal elements are separated by commas. But the element cannot be assigned a second value, which is equivalent to a read-only list.
Tuple = (1, 2, 4)

Dic = {"k1": "v1", "k2": "v2 "}
Dic ["k1"]

Dic = {"k1" => 'v1 ', 'k2' => 'v2 '}
Dic = {: k1 => 'v1 ',: k2 => 'v2 '}
Dic = {k1: 'v1 ', k2: 'v2 '}
Dic ["k1"]
Dic [: k1]

The condition determines that the values of 0, null, and false in the python programming language are false.
The ruby programming language specifies that nil and false are false.

If condition:
Code ..
Elif codition:
Code ..
Code ..

If/unless condition [then]
Code ..
Elsif condition [then]
Code ..
Code ..

Simple statement
If codition: code
Code if condition

Loop python
While condition:
Code ..
Code ..

For var in sequ:
Code ..
Code ..

While conditin [do]

For var in sequ [do]

Function python
The function code block starts with the def keyword, followed by the Function Identifier name and parentheses ().
Any input parameters and independent variables must be placed in the middle of parentheses. Parentheses can be used to define parameters.
The first line of a function can selectively use the document string-used to store the function description.
The function content starts with a colon and is indented.
Return [exp] ends the function and returns a value to the caller selectively. Return without expression is equivalent to return None.

All parameters (independent variables) are passed by reference in Python. If you modify parameters in the function, the original parameters are also changed in the function that calls the function.
Def say (something, age = 10, * var_params ):
'Function description'
Return [exp]

Anonymous Functions
Python uses lambda to create anonymous functions.
Lambda is just an expression, and the function is much simpler than def.
The body of lambda is an expression rather than a code block. Only limited logic can be encapsulated in lambda expressions.
Lambda [arg1 [, arg2,... argn]: expression

Each method in Ruby returns a value by default, which is the value of the last statement.
Def say (something, age = 10, * var_params)

In Ruby, the code between {} Or do... end is a code block.
A code block can only appear behind a method. It is followed by the same line of the last parameter of the method. Generally, the yield keyword calls the code in the code block.

Module python
The module enables you to logically organize your Python code segments.
Assigning relevant code to a module makes your code easier to use and understand.
The module is also a Python object and has random name attributes for binding or reference.
Simply put, a module is a file that saves Python code. The module can define functions, classes, and variables. The module can also contain executable code

A Module is a combination of methods, classes, and constants. The Module provides two benefits.
The module provides a namespace to avoid name conflicts.
The module implements the mixin device.
A Module defines a namespace, which is equivalent to a sandbox in which your methods and constants do not conflict with the method constants in other places.

Class python
If a Python function, class method, or attribute name starts with two underscores (but not ends), it is private; all others are public.

Class Method
After Python2.2, you can use @ classmethod to create class methods. The first parameter is the class, and the convention is written as cls.

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

No constants in Python

Class Vector:

Class_var = 0 # class variable

Def _ init _ (self, a, B ):

Self. instance_var = a # instance variable

Def _ del _ (self ):

@ Classmethod
Def say (cls ):
Code ..

Support multi-Inheritance
Class B:
Class C (A, B ):

Everything in Ruby is an object, including a constant.
For example, you can use the. class Attribute to view the type of an object. You can see that the type of constant 1 is Fixnum, and 1 is just an instance of Fixnum.

In Ruby, classes start from class and end, and the conventions for the first letter of the class name are capitalized.
In Ruby, the method starts with def and ends with end. The conventions for the first letter of the method name are in lower case.
The first letter of a local variable in Ruby is in lower case.
The constructor name in Ruby is initialize.
The leading @ character of the member variable (instance variable) in Ruby, which is declared and initialized in initialize.
Attributes in Ruby are attr, attr_reader, attr_writer, and attr_accessor.
The $ identifier of the global variable in Ruby.
Constants (constants) in Ruby start with uppercase letters, and the conventions are all uppercase letters.

Initalize Method

When Ruby creates a new object, it always looks for a method named initialize and executes it. Therefore, we can simply add the default value to the Real Variable through an initialize method.

Class Person

Def initialize ()
Puts "hello! "

# Def initialize # () is omitted.
# Puts "hello! "
# End

# Default parameter values
# Def initialize (param = "1900lab") # parameters with default values
# Puts "hello! "+ Param
# End

# Variable Length Parameter
Def youInput (* names)
Puts "input # {names. join (",")}! "

P = Person. new ()
Like p = Person. new, no parameter () can be omitted.

The purpose is to quickly generate a read/write method.

Attr: attr1, key
Attr_reader: attr1,: attr2
Attr_writer: attr1,: attr2
Attr_accessor: attr1,: attr2

Attr is generally followed by a symbolic parameter, and the second parameter is a Boolean parameter, used to indicate whether it is a symbolic parameter to generate a write method. The default value is false. Only the read method is generated, and no write method is generated.
Attr_reader is generally followed by a symbolic parameter, which defines one or more read-only attributes to indicate the generation of read methods for symbolic parameters.
Attr_writer is generally followed by a symbolic parameter and defines one or more write-only attributes to indicate the write Method for symbolic parameters.
Attr_accessor is generally followed by a symbolic parameter, which defines one or more read/write attributes and is used to indicate that a symbolic parameter is used to generate a read/write method.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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: 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.