Ruby strings, conditions, loops, arrays, hashes, class basic action notes _ruby topics

Source: Internet
Author: User
Tags arrays hash

One, string operation

string interpolation

1.#{}: Any legitimate Ruby code placed in #{} will be evaluated and replaced with an evaluation result inserted in the original location

2. Single and double quotation marks differ:

Double quotes allow character escape, single quotes not allowed to escape, what characters are inside, what characters are seen by the user
Single quotes do not allow character interpolation

String split

1. Split by Space: String.Split (") String connection

Method one, ' Ruby ' + ' Monk ', Stdout:rubymonk
Method Two, "Monk". Concat ("Ruby") Stdout:monkruby
Method III, "Ruby" << "Monk" Stdout:rubymonk

SUBSTRING substitution

Replace the first occurrence of the search target: "I should look in your problem when I get Time". Sub (' I ', ' We ')
Replace any strings that match the criteria: "I should look in your problem when I get Time". Gsub (' i ', ' We ')

Ii. conditions and cycles: control structure in Ruby

Ruby Boolean expression

Ruby uses the = = operator to compare objects: Name = = "Bob"
Take non-expression:! (name = = ' Bob ')

If.. else structure in the Ruby language,? And: You can understand that they correspond to loops in the "then" and "Else" Ruby languages, respectively.

1. Infinite cycle

Copy Code code as follows:

Loopdo
.....
End

2. Execute code fragment n times

Copy Code code as follows:
Times do
......
End

Three, array

create an empty array ' [] ' or array.new

Querying data in an array

Copy Code code as follows:
[1, 2, 3, 4, 5] [2]

The result is
Copy Code code as follows:
3

Ruby's index starts with 0 starting at the beginning, starting at the end, starting with-1.

The growth of the array

Copy Code code as follows:

[1, 2, 3, 4, 5]<< "Woot" results
[1, 2, 3, 4, 5, "Woot"]

Basic array Operations

1. Array transformation

Copy Code code as follows:
[1, 2, 3, 4, 5].map {|i| i + 1}

Results
Copy Code code as follows:
[2, 3, 4, 5, 6]

2. Filter array elements

Copy Code code as follows:
[1,2,3,4,5,6,7].delete_if{|i| i < 4}

Results
Copy Code code as follows:
[2, 4, 6]


Extract a string longer than five letters
Copy Code code as follows:
names = [' Rock ', ' paper ', ' scissors ', ' lizard ', ' Spock ']
Names.select {|word| word.length > 5}

Results
Copy Code code as follows:
["Scissors", "lizard"]

3. Delete Element

Delete the element ' 5 ' of the following array
Copy Code code as follows:
[1,3,5,4,6,7].delete 5
[1,2,3,4,5,6,7].delete_if{|i| i < 4}

Iteration 1.each Loop

Copy Code code as follows:
Array = [1, 2, 3, 4, 5]
Array.each do |i|
Puts I
End

Four, Ruby Hash

1. Creating a hash null hash can be defined using two curly braces {}, hash.new

Copy Code code as follows:

Restaurant_menu = {
"Ramen" => 3,
"Dal Makhani" => 4,
"Tea" => 2
}

2. From the Greek Restaurant_menu to obtain a bowl of ramen (ramen) Price
Restaurant_menu["Ramen"] results

3. Modify hash Add New item

Copy Code code as follows:

Restaurant_menu = {}
restaurant_menu["Dal makhani"] = 4.5
restaurant_menu["Tea"] = 2 4. Traverse Hash
Restaurant_menu = {"Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2}
Restaurant_menu.each do | Item, Price |
Puts "#{item}: $#{price}"
End

Results

Copy Code code as follows:

Ramen: $
Dal Makhani: $
Coffee: $

Use each method to increase the price of all items in Restaurant_menu by 10%

Copy Code code as follows:
Restaurant_menu = {"Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2}
Restaurant_menu.each do |item, price|
Restaurant_menu[item] = Price + (Price * 0.1)
End

5. Taking keys and values from the Greek
Each hash object has 2 methods: keys and values.
The Keys method returns an array containing all the keys in the hash; Similarly, the values method returns an array that contains all of the values.
Get all the keys in Restaurant_menu
Copy Code code as follows:
Restaurant_menu = {"Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2}
Restaurant_menu.keys

Results
Copy Code code as follows:

["Ramen", "Dal Makhani", "Coffee"]

Five, class

Ruby uses a two-space indent convention, where code blocks are usually closed with keyword end, and invoking method new on a class creates an instance

Copy Code code as follows:
Object.new

1. Build Your own class

Copy Code code as follows:
Class Rectangle
End

Example of calculating the circumference and area of a rectangle

Copy Code code as follows:
Class Rectangle
Def initialize (length, breadth)
@length = length
@breadth = Breadth
End

def Perimeter
2 * (@length + @breadth)
End

def area
@length * @breadth
End
End

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.