ruby学习笔记(3)
本节课主要4部分内容如下:
Method Missing、More on Strings、Simple Constructs、Ruby Arrays
3.1 Method Missing
在ruby中,如果执行某对象的方法找不到时,则会报NoMethodError
但如果定义了方法method_missing,则错误会被该方法拦截
3.2 More on Strings
ruby中的string是mutable的,这与java有明显的不同
1) 常用的不会修改string原始字符串的函数:upcase,downcase,swapcase......
2) 常用的会修改string原始字符串的函数:upcase!,downcase!,swapcase! capitalize!......
注意: 叹号!在这里的作用,很不可思议吧?
3) 之前我们提到,string可由单引号或双引号定义,而单引号的效率会更高,
主要原因在于双引号处理的过程更复杂,过程如下:
a. 查找替换符\,如果找到执行替换操作
b. 查找符号#,如果找到,计算表达式#{expression} #学习笔记2中有这个例子
注意:对单引号定义的string,则只会处理步骤a
4)String的几个特殊方法
String. methods.sort #列出string class的所有方法,sort用来排序
String. instance_methods.sort #列出string instance 的所有方法
String. instance_methods(false).sort #列出string中不包括从父类继承的instance所有方法
5)String的比较
(1) == #tests two strings for identical content
(2) String.eql? #tests two strings for identical content
(3) String.equal? #tests whether two strings are the same object
注意:(1),(2)是比较内容,结果一样
(3)比较的是引用(是否同一对象)
通常定义String的数组时,使用单引号和逗号,
names1 = [ 'ann', 'richard', 'william', 'susan', 'pat' ]
# puts names1[0] # ann
# puts names1[3] # susan
但如果使用%w,可以大大简化操作
# names2 = %w{ ann richard william susan pat }
# puts names2[0] # ann
# puts names2[3] # susan
3.3 Simple Constructs
1) ruby中,nil和false 被认为是 false 的,其他任何(true,0,....)都是true
2) ruby的简单结构主要包括
if
end
if
else
end
if
elsif
end
unless
end
while
end
3.4 Ruby Arrays
1) 数组索引从0开始
2) 数组可以动态增加
array = ['Hello', 'Goodbye']
array[2] = 'world'
array[3] = '....'
3)可以使用each获取数组元素
languages = ['Pune', 'Mumbai', 'Bangalore']
languages.each do |lang|
puts 'I love ' + lang + '!'
end
3.5 总结
3.6 作业
1. Write a Ruby program that asks for a year and then displays to the user whether the year entered by
him/her is a leap year or not.
2. Write a method leap_year. Accept a year value from the user,
check whether it's a leap year and then display the number of minutes in that year.
3. Write a Ruby program that,
when given an array as collection = [1, 2, 3, 4, 5] it calculates the sum of its elements.
4. Write a Ruby program that, when given an array as collection = [12, 23, 456, 123, 4579]
it displays for each number, whether it is odd or even.
5.Write a program that processes a string "Welcome to the forum.\nHere you can learn Ruby.\nAlong with other members.\n" a line at a time, using all that we have learned so far. The expected output is:
# Line 1: Welcome to the forum.
# Line 2: Here you can learn Ruby.
# Line 3: Along with other members.
本节课主要4部分内容的原文链接:
3.1 Method Missing
在ruby中,如果执行某对象的方法找不到时,则会报NoMethodError
但如果定义了方法method_missing,则错误会被该方法拦截
class
Dummy
def method_missing(m, * args) #可变参数的定义
puts " There's no method called #{m} here -- please try again. "
end
end
Dummy. new .anything
输出结果:There ' s no method called anything here -- please try again
def method_missing(m, * args) #可变参数的定义
puts " There's no method called #{m} here -- please try again. "
end
end
Dummy. new .anything
输出结果:There ' s no method called anything here -- please try again
3.2 More on Strings
ruby中的string是mutable的,这与java有明显的不同
1) 常用的不会修改string原始字符串的函数:upcase,downcase,swapcase......
2) 常用的会修改string原始字符串的函数:upcase!,downcase!,swapcase! capitalize!......
注意: 叹号!在这里的作用,很不可思议吧?
3) 之前我们提到,string可由单引号或双引号定义,而单引号的效率会更高,
主要原因在于双引号处理的过程更复杂,过程如下:
a. 查找替换符\,如果找到执行替换操作
b. 查找符号#,如果找到,计算表达式#{expression} #学习笔记2中有这个例子
注意:对单引号定义的string,则只会处理步骤a
4)String的几个特殊方法
String. methods.sort #列出string class的所有方法,sort用来排序
String. instance_methods.sort #列出string instance 的所有方法
String. instance_methods(false).sort #列出string中不包括从父类继承的instance所有方法
5)String的比较
(1) == #tests two strings for identical content
(2) String.eql? #tests two strings for identical content
(3) String.equal? #tests whether two strings are the same object
注意:(1),(2)是比较内容,结果一样
(3)比较的是引用(是否同一对象)
puts
'
test
'
==
'
test
'
#结果为true
puts ' test ' .eql ? ' test ' # 结果为 true
puts ' test ' .equal ? ' test ' # 结果为 false
6)
%w的使用
puts ' test ' .eql ? ' test ' # 结果为 true
puts ' test ' .equal ? ' test ' # 结果为 false
通常定义String的数组时,使用单引号和逗号,
names1 = [ 'ann', 'richard', 'william', 'susan', 'pat' ]
# puts names1[0] # ann
# puts names1[3] # susan
但如果使用%w,可以大大简化操作
# names2 = %w{ ann richard william susan pat }
# puts names2[0] # ann
# puts names2[3] # susan
3.3 Simple Constructs
1) ruby中,nil和false 被认为是 false 的,其他任何(true,0,....)都是true
2) ruby的简单结构主要包括
if
end
if
else
end
if
elsif
end
unless
end
while
end
3.4 Ruby Arrays
1) 数组索引从0开始
2) 数组可以动态增加
array = ['Hello', 'Goodbye']
array[2] = 'world'
array[3] = '....'
3)可以使用each获取数组元素
languages = ['Pune', 'Mumbai', 'Bangalore']
languages.each do |lang|
puts 'I love ' + lang + '!'
end
3.5 总结
*
method_missing gives you a way to intercept unanswerable messages and handle them gracefully.
* Refer to the String documentation to use the various methods available.
* For double - quoted string literals, Ruby looks for substitutions - sequences that start with a backslash character - and replaces them with some binary value or does expression interpolation ie. within the string, the sequence #{expression} is replaced by the value of the expression.
* It is to be noted that every time a string literal is used in an assignment or as a parameter, a new String object is created.
* % w is a common usage in strings.
* Observe how one can list all the methods of a class or object.
* Comparing two strings for equality can be done by == or .eql ? ( for identical content) and .equal ? ( for identical objects).
* Observe the usage of constructs: if else end, while , if elsif end
* Case Expressions: This form is fairly close to a series of if statements: it lets you list a series of conditions and execute a statement corresponding to the first one that ' s true. case returns the value of the last expression executed. Usage: case when else end
* Ruby also has a negated form of the if statement, the unless end.
* An Array is just a list of items in order. Every slot in the list acts like a variable: you can see what object a particular slot points to, and you can make it point to a different object. You can make an array by using square brackets.
* Arrays are indexed by integers and the index starts from 0 .
* A trailing comma in an array declaration is ignored.
* You can access an array beyond its boundary limits; it will return nil.
* We can add more elements to an existing array.
* Refer the Array documentation for a list of methods.
* The method each ( for any object) is an iterator that extracts each element of the array. The method each allows us to do something (whatever we want) to each object the array points to.
* The variable inside the " goalposts " ie. | | refers to each item in the array as it goes through the loop. You can give this any name you want.
* The do and end identify a block of code that will be executed for each item.
* Refer to the String documentation to use the various methods available.
* For double - quoted string literals, Ruby looks for substitutions - sequences that start with a backslash character - and replaces them with some binary value or does expression interpolation ie. within the string, the sequence #{expression} is replaced by the value of the expression.
* It is to be noted that every time a string literal is used in an assignment or as a parameter, a new String object is created.
* % w is a common usage in strings.
* Observe how one can list all the methods of a class or object.
* Comparing two strings for equality can be done by == or .eql ? ( for identical content) and .equal ? ( for identical objects).
* Observe the usage of constructs: if else end, while , if elsif end
* Case Expressions: This form is fairly close to a series of if statements: it lets you list a series of conditions and execute a statement corresponding to the first one that ' s true. case returns the value of the last expression executed. Usage: case when else end
* Ruby also has a negated form of the if statement, the unless end.
* An Array is just a list of items in order. Every slot in the list acts like a variable: you can see what object a particular slot points to, and you can make it point to a different object. You can make an array by using square brackets.
* Arrays are indexed by integers and the index starts from 0 .
* A trailing comma in an array declaration is ignored.
* You can access an array beyond its boundary limits; it will return nil.
* We can add more elements to an existing array.
* Refer the Array documentation for a list of methods.
* The method each ( for any object) is an iterator that extracts each element of the array. The method each allows us to do something (whatever we want) to each object the array points to.
* The variable inside the " goalposts " ie. | | refers to each item in the array as it goes through the loop. You can give this any name you want.
* The do and end identify a block of code that will be executed for each item.
3.6 作业
1. Write a Ruby program that asks for a year and then displays to the user whether the year entered by
him/her is a leap year or not.
2. Write a method leap_year. Accept a year value from the user,
check whether it's a leap year and then display the number of minutes in that year.
3. Write a Ruby program that,
when given an array as collection = [1, 2, 3, 4, 5] it calculates the sum of its elements.
4. Write a Ruby program that, when given an array as collection = [12, 23, 456, 123, 4579]
it displays for each number, whether it is odd or even.
5.Write a program that processes a string "Welcome to the forum.\nHere you can learn Ruby.\nAlong with other members.\n" a line at a time, using all that we have learned so far. The expected output is:
# Line 1: Welcome to the forum.
# Line 2: Here you can learn Ruby.
# Line 3: Along with other members.
#
1
.Write a Ruby program that asks
for
a year and then displays to the user
# whether the year entered by him / her is a leap year or not.
def is_leap_year(year)
if (year.to_i % 4 == 0 && year.to_i % 100 != 0 ) || (year.to_i % 400 == 0 )
return true
end
end
puts ' Please input a year number: '
STDOUT.flush
year = gets.chomp
if is_leap_year(year )
puts " #{year} is a leap year "
else
puts " #{year} is not a leap year "
end
# -----------------------------------------------------
# 2 Write a method leap_year. Accept a year value from the user,
# check whether it ' s a leap year and
# then display the number of minutes in that year.
def is_leap_year(year)
if (year.to_i % 4 == 0 && year.to_i % 100 != 0 ) || (year.to_i % 400 == 0 )
return true
end
end
puts ' Please input a year number: '
STDOUT.flush
year = gets.chomp
if is_leap_year(year)
puts " #{year} is a leap year "
puts " #{year} has #{366 * 24 *60} minutes "
else
puts " #{year} is not a leap year "
puts " #{year} has #{365 * 24 *60} minutes "
end
# ----------------------------------------------
# 3 Write a Ruby program that,
# when given an array as collection = [ 1 , 2 , 3 , 4 , 5 ] it calculates the sum of its elements.
def calculate_sum(array)
sum = 0
array.each do | num |
sum = sum + num
end
return sum
end
puts calculate_sum([ 1 , 2 , 3 , 4 , 5 ])
# ----------------------------------------------
# 4 Write a Ruby program that, when given an array as collection = [ 12 , 23 , 456 , 123 , 4579 ]
# it displays for each number, whether it is odd or even.
def display_num_stauts(array)
array.each do | num |
if num % 2 == 0
puts num.to_s + ' is even number '
else
puts num.to_s + ' is odd number '
end
end
end
display_num_stauts([ 12 , 23 , 456 , 123 , 4579 ])
# ----------------------------------------------
# 5 Write a program that processes a string s =
# " Welcome to the forum.\nHere you can learn Ruby.\nAlong with other members.\n "
# a line at a time, using all that we have learned so far. The expected output is:
# Line 1 : Welcome to the forum.
# Line 2 : Here you can learn Ruby.
# Line 3 : Along with other members.
s = " Welcome to the forum.\nHere you can learn Ruby.\nAlong with other members.\n "
a = s.split( " \n " ).to_a
a.each do | str |
# puts " Line " + a.index(str).to_s + str
#{a.index(str)} "
puts " Line #{a.index(str)} " + str
end
---------------------------------------------------------------------------------------------------------
# whether the year entered by him / her is a leap year or not.
def is_leap_year(year)
if (year.to_i % 4 == 0 && year.to_i % 100 != 0 ) || (year.to_i % 400 == 0 )
return true
end
end
puts ' Please input a year number: '
STDOUT.flush
year = gets.chomp
if is_leap_year(year )
puts " #{year} is a leap year "
else
puts " #{year} is not a leap year "
end
# -----------------------------------------------------
# 2 Write a method leap_year. Accept a year value from the user,
# check whether it ' s a leap year and
# then display the number of minutes in that year.
def is_leap_year(year)
if (year.to_i % 4 == 0 && year.to_i % 100 != 0 ) || (year.to_i % 400 == 0 )
return true
end
end
puts ' Please input a year number: '
STDOUT.flush
year = gets.chomp
if is_leap_year(year)
puts " #{year} is a leap year "
puts " #{year} has #{366 * 24 *60} minutes "
else
puts " #{year} is not a leap year "
puts " #{year} has #{365 * 24 *60} minutes "
end
# ----------------------------------------------
# 3 Write a Ruby program that,
# when given an array as collection = [ 1 , 2 , 3 , 4 , 5 ] it calculates the sum of its elements.
def calculate_sum(array)
sum = 0
array.each do | num |
sum = sum + num
end
return sum
end
puts calculate_sum([ 1 , 2 , 3 , 4 , 5 ])
# ----------------------------------------------
# 4 Write a Ruby program that, when given an array as collection = [ 12 , 23 , 456 , 123 , 4579 ]
# it displays for each number, whether it is odd or even.
def display_num_stauts(array)
array.each do | num |
if num % 2 == 0
puts num.to_s + ' is even number '
else
puts num.to_s + ' is odd number '
end
end
end
display_num_stauts([ 12 , 23 , 456 , 123 , 4579 ])
# ----------------------------------------------
# 5 Write a program that processes a string s =
# " Welcome to the forum.\nHere you can learn Ruby.\nAlong with other members.\n "
# a line at a time, using all that we have learned so far. The expected output is:
# Line 1 : Welcome to the forum.
# Line 2 : Here you can learn Ruby.
# Line 3 : Along with other members.
s = " Welcome to the forum.\nHere you can learn Ruby.\nAlong with other members.\n "
a = s.split( " \n " ).to_a
a.each do | str |
# puts " Line " + a.index(str).to_s + str
#{a.index(str)} "
puts " Line #{a.index(str)} " + str
end
本节课主要4部分内容的原文链接:
- Method Missing
http://rubylearning.com/satishtalim/ruby_method_missing.html - More on Strings
http://rubylearning.com/satishtalim/more_on_strings.html - Simple Constructs
http://rubylearning.com/satishtalim/simple_constructs.html - Ruby Arrays
http://rubylearning.com/satishtalim/ruby_arrays.html