- 浏览: 2541019 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
Learn to Program(3)
9. Classes
Objects in Ruby are always capitalized. String, Integer, Float, Array...
a = Array.new([1,3,3])
b = String.new('carl')
c = Time.new
puts a.to_s
puts b.to_s
puts c.to_s
results are :
[1, 3, 3]
carl
2011-08-10 16:39:01 +0800
9.1 The Time Class
time = Time.new
time2 = time + 60 # one minute later
puts time
puts time2
puts Time.mktime(1982,4,5)
puts Time.mktime(1982,4,5,23,50,59)
9.2 The Hash Class
Hashes are a lot like arrays. It is just like the Map class in Java.
colorArray = []
colorHash = {}
colorArray[0] = 'red'
colorArray[1] = 'green'
colorHash['strings'] = 'red'
colorHash['numbers'] = 'green'
colorHash['keywords']= 'blue'
colorArray.each do |color|
puts color
end
colorHash.each do |codeType,color|
puts codeType + ": " + color
end
9.3 Extending Classes
It seems a miracle to extends the class here.
class Integer
def to_eng
if self == 5
english = 'five'
end
if self == 6
english = 'six'
end
english
end
end
puts 5.to_eng
puts 6.to_eng
9.4 Creating Classes
class Die
def roll
1 + rand(6)
end
end
dice = [Die.new,Die.new,Die.new]
dice.each do |die|
puts die.roll
end
9.5 Instance Variables
An instance of a class is just an object of that class. So instance variables are just an object's variables.To tell instance variables from
local variables, they have @ in front of their names:
class Die
def roll
@number = 1 + rand(6)
end
def show
@number
end
end
die = Die.new
die.roll
puts die.show
die.roll
puts die.show
We can initial the class first.
class Die
def initialize
roll
end
...snip...
end
When an object is created, its initialize method (if it has one defined) is always called.
10. Blocks and Procs
It is the ability to take a block of code (code in between do and end), wrap it up in an object (called a proc), store it in a variable or pass it to a method, and run the code in the block whenever you feel like.
toast = Proc.new do
puts 'Cheers!'
end
toast.call
toast.call
Proc which is supposed to be short for 'procedure'. It rhymes with 'block'.
It is even more like a method, because blocks can take parameters.
doyoulike = Proc.new do |goodthing|
puts 'I really like ' + goodthing + '!'
end
doyoulike.call 'chocolate'
In particular, you can't pass methods into other methods, but you can pass procs into methods.
Methods can't return other methods, but they can return procs.
The root reason is procs are objects, methods are not.
10.1 Methods Which Take Procs
def doSelfImportantly someProc
puts 'Everybody just HOLD ON! I have something to do...'
someProc.call
puts 'Ok everyone, I\'m done. Go on with what you were doing.'
end
sayHello = Proc.new do
puts 'hello'
end
sayGoodbye = Proc.new do
puts 'goodbye'
end
doSelfImportantly sayHello
doSelfImportantly sayGoodbye
Complex example.
def doUntilFalse firstInput, someProc
input = firstInput
output = firstInput
while output
input = output
output = someProc.call input
end
input
end
buildArrayOfSquares = Proc.new do |array|
lastNumber = array.last
if lastNumber <= 0
false
else
array.pop # Take off the last number...
array.push lastNumber*lastNumber # ...and replace it with its square...
array.push lastNumber-1 # ...followed by the next smaller number.
end
end
alwaysFalse = Proc.new do |justIgnoreMe|
false
end
puts doUntilFalse([5], buildArrayOfSquares).inspect
puts doUntilFalse('I\'m writing this at 3:00 am; someone knock me out!', alwaysFalse)
The inspect method is a lot like to_s.
10.2 Methods Which Return Procs
def compose proc1, proc2
Proc.new do |x|
proc2.call(proc1.call(x))
end
end
squareIt = Proc.new do |x|
x * x
end
doubleIt = Proc.new do |x|
x + x
end
doubleThenSquare = compose doubleIt, squareIt
squareThenDouble = compose squareIt, doubleIt
puts doubleThenSquare.call(5)
puts squareThenDouble.call(5)
Make 2 procs to 1 proc and return proc in the method.
10.3 Passing Blocks (Not Procs) Into Methods
class Array
def eachEven(&wasABlock_nowAProc)
isEven = true # We start with "true" because arrays start with 0, which is even.
self.each do |object|
if isEven
wasABlock_nowAProc.call object
end
isEven = (not isEven) # Toggle from even to odd, or odd to even.
end
end
end
['apple', 'bad apple', 'cherry', 'durian'].eachEven do |fruit|
puts 'Yum! I just love '+fruit+' pies, don\'t you?'
end
# Remember, we are getting the even-numbered elements
# of the array, all of which happen to be odd numbers,
# just because I like to cause problems like that.
[1, 2, 3, 4, 5].eachEven do |oddBall|
puts oddBall.to_s+' is NOT an even number!'
end
&name, bring block to the methods. Another example.
def profile descriptionOfBlock, &block
startTime = Time.now
block.call
duration = Time.now - startTime
puts descriptionOfBlock+': '+duration.to_s+' seconds'
end
profile '25000 doublings' do
number = 1
25000.times do
number = number + number
end
puts number.to_s.length.to_s+' digits' # That is, the number of digits in this HUGE number.
end
profile 'count to a million' do
number = 0
1000000.times do
number = number + 1
end
end
results are as follow:
7526 digits
25000 doublings: 0.1092 seconds
count to a million: 0.124801 seconds
references:
http://pine.fm/LearnToProgram/?Chapter=09
9. Classes
Objects in Ruby are always capitalized. String, Integer, Float, Array...
a = Array.new([1,3,3])
b = String.new('carl')
c = Time.new
puts a.to_s
puts b.to_s
puts c.to_s
results are :
[1, 3, 3]
carl
2011-08-10 16:39:01 +0800
9.1 The Time Class
time = Time.new
time2 = time + 60 # one minute later
puts time
puts time2
puts Time.mktime(1982,4,5)
puts Time.mktime(1982,4,5,23,50,59)
9.2 The Hash Class
Hashes are a lot like arrays. It is just like the Map class in Java.
colorArray = []
colorHash = {}
colorArray[0] = 'red'
colorArray[1] = 'green'
colorHash['strings'] = 'red'
colorHash['numbers'] = 'green'
colorHash['keywords']= 'blue'
colorArray.each do |color|
puts color
end
colorHash.each do |codeType,color|
puts codeType + ": " + color
end
9.3 Extending Classes
It seems a miracle to extends the class here.
class Integer
def to_eng
if self == 5
english = 'five'
end
if self == 6
english = 'six'
end
english
end
end
puts 5.to_eng
puts 6.to_eng
9.4 Creating Classes
class Die
def roll
1 + rand(6)
end
end
dice = [Die.new,Die.new,Die.new]
dice.each do |die|
puts die.roll
end
9.5 Instance Variables
An instance of a class is just an object of that class. So instance variables are just an object's variables.To tell instance variables from
local variables, they have @ in front of their names:
class Die
def roll
@number = 1 + rand(6)
end
def show
@number
end
end
die = Die.new
die.roll
puts die.show
die.roll
puts die.show
We can initial the class first.
class Die
def initialize
roll
end
...snip...
end
When an object is created, its initialize method (if it has one defined) is always called.
10. Blocks and Procs
It is the ability to take a block of code (code in between do and end), wrap it up in an object (called a proc), store it in a variable or pass it to a method, and run the code in the block whenever you feel like.
toast = Proc.new do
puts 'Cheers!'
end
toast.call
toast.call
Proc which is supposed to be short for 'procedure'. It rhymes with 'block'.
It is even more like a method, because blocks can take parameters.
doyoulike = Proc.new do |goodthing|
puts 'I really like ' + goodthing + '!'
end
doyoulike.call 'chocolate'
In particular, you can't pass methods into other methods, but you can pass procs into methods.
Methods can't return other methods, but they can return procs.
The root reason is procs are objects, methods are not.
10.1 Methods Which Take Procs
def doSelfImportantly someProc
puts 'Everybody just HOLD ON! I have something to do...'
someProc.call
puts 'Ok everyone, I\'m done. Go on with what you were doing.'
end
sayHello = Proc.new do
puts 'hello'
end
sayGoodbye = Proc.new do
puts 'goodbye'
end
doSelfImportantly sayHello
doSelfImportantly sayGoodbye
Complex example.
def doUntilFalse firstInput, someProc
input = firstInput
output = firstInput
while output
input = output
output = someProc.call input
end
input
end
buildArrayOfSquares = Proc.new do |array|
lastNumber = array.last
if lastNumber <= 0
false
else
array.pop # Take off the last number...
array.push lastNumber*lastNumber # ...and replace it with its square...
array.push lastNumber-1 # ...followed by the next smaller number.
end
end
alwaysFalse = Proc.new do |justIgnoreMe|
false
end
puts doUntilFalse([5], buildArrayOfSquares).inspect
puts doUntilFalse('I\'m writing this at 3:00 am; someone knock me out!', alwaysFalse)
The inspect method is a lot like to_s.
10.2 Methods Which Return Procs
def compose proc1, proc2
Proc.new do |x|
proc2.call(proc1.call(x))
end
end
squareIt = Proc.new do |x|
x * x
end
doubleIt = Proc.new do |x|
x + x
end
doubleThenSquare = compose doubleIt, squareIt
squareThenDouble = compose squareIt, doubleIt
puts doubleThenSquare.call(5)
puts squareThenDouble.call(5)
Make 2 procs to 1 proc and return proc in the method.
10.3 Passing Blocks (Not Procs) Into Methods
class Array
def eachEven(&wasABlock_nowAProc)
isEven = true # We start with "true" because arrays start with 0, which is even.
self.each do |object|
if isEven
wasABlock_nowAProc.call object
end
isEven = (not isEven) # Toggle from even to odd, or odd to even.
end
end
end
['apple', 'bad apple', 'cherry', 'durian'].eachEven do |fruit|
puts 'Yum! I just love '+fruit+' pies, don\'t you?'
end
# Remember, we are getting the even-numbered elements
# of the array, all of which happen to be odd numbers,
# just because I like to cause problems like that.
[1, 2, 3, 4, 5].eachEven do |oddBall|
puts oddBall.to_s+' is NOT an even number!'
end
&name, bring block to the methods. Another example.
def profile descriptionOfBlock, &block
startTime = Time.now
block.call
duration = Time.now - startTime
puts descriptionOfBlock+': '+duration.to_s+' seconds'
end
profile '25000 doublings' do
number = 1
25000.times do
number = number + number
end
puts number.to_s.length.to_s+' digits' # That is, the number of digits in this HUGE number.
end
profile 'count to a million' do
number = 0
1000000.times do
number = number + 1
end
end
results are as follow:
7526 digits
25000 doublings: 0.1092 seconds
count to a million: 0.124801 seconds
references:
http://pine.fm/LearnToProgram/?Chapter=09
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 467NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 328Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 428Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 376Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 465NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 413Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 330Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 242GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 443GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 320GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 306Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 285Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 302Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 278NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 255Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 564NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 256Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 359Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 363Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
Learn to Program with Python 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者...
Learn to Program with Python:Take your first steps in programming and learn the powerful Python programming language,高清文字版
《Learn to Program》是一本专为初学者设计的编程教程,旨在帮助读者掌握编程基础知识,以英文版的形式呈现,让全球的学习者都能接触到这一宝贵的资源。在这个数字化的时代,编程技能已经成为一项重要的技能,不论是...
### 学习C++编程:McGraw-Hill出版社的《Learn To Program With C++》概览 #### 书籍背景与概述 《Learn To Program With C++》是McGraw-Hill出版社出版的一本关于C++编程的学习指南。这本书旨在为初学者提供一个...
https://www.amazon.cn/dp/148421868X/ref=sr_1_1?ie=UTF8&qid=1524202763&sr=8-1&keywords=learn+to+program+with+python 亚马逊上468原价的书,高清英文原版。
《Learn to Program with Small Basic》是一本专门针对儿童和少年编程教学的书籍,由Majed Marji和Ed Price编写,通过微软出品的Small Basic编程语言教授编程知识。该书旨在为初学者提供一种易于学习的编程方式,使...
Introduction to Programming_ Learn to program with Data StructuresIntroduction to Programming_ Learn to program with Data StructuresIntroduction to Programming_ Learn to program with Data ...
In Learn to Program with Scratch, author Majed Marji uses Scratch to explain the concepts essential to solvin g real-world programming problems. The labeled, color-coded blocks plainly show
3. **分步教程**:书中包含一系列由简入难的编程练习,每个练习都附有详细的指导说明。 4. **Python编程基础**:从变量、循环到函数等,本书涵盖了Python编程的基础概念和技术。 5. **项目驱动**:通过完成一个个小...
Learn to Program with C teaches computer programming to the complete beginner using the native C language. As such, it assumes you have no knowledge whatsoever about programming. The main goal of this...
《Learn to Program with C》这本书旨在引导编程初学者通过学习C语言来掌握计算机编程的基础知识。C语言自问世以来,一直以其高效、灵活的特点深受程序员喜爱,并广泛应用于操作系统、嵌入式系统、游戏开发等多个...