Learn to Program(2)

本博客介绍编程中的流程控制方法,如条件判断、分支选择和循环使用,并通过实例展示如何操作数组和迭代器。包括比较方法、条件分支、循环、数组应用和自定义方法的创建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Learn to Program(2)

6. Flow Control
6.1 Comparison Method
puts 'cat' < 'dog'
result is true, because cat comes before dog in the directory.

6.2 Branching
That is branching, if what comes after the if is true, we run the code between the if and the end. If what comes after the if is false,
we don't.
if name == 'carl'
puts 'that is an nice name'

6.3 Looping
command = ''
while command != 'bye'
puts command
command = gets.chomp
end
puts 'The program comes an end'

7 Arrays and Iterators
[], [5], ['Hello', 'Goodbye'], [89.9, 'test', [true, false]]
names = ['Ada', 'Belle', 'Chris']
puts '1' + names.to_s
puts '2' + names[0]
puts '3' + names[1]
puts '4' + names[2]
1["Ada", "Belle", "Chris"]
2Ada
3Belle
4Chris

7.1 The Method each
each allows us to do something (whatever we want) to each object the array points to.
languages = ['English', 'German', 'Ruby']
languages.each do |lang|
puts 'I love ' + lang + '!'
end

I love English!
I love German!
I love Ruby!

3.times do
puts 'go'
end
go go go

7.2 More Array Methods
foods = ['artichoke', 'brioche', 'caramel']
puts foods.to_s
puts foods.join(', ')

["artichoke", "brioche", "caramel"]
artichoke, brioche, caramel

200.times do
puts []
end

puts an empty array 200 times means nothing.

favorites = []
favorites.push 'carl'
favorites.push 'kiko'
puts '0 =' + favorites[0]
puts 'last =' + favorites.last
puts 'length =' + favorites.length.to_s
puts 'pop =' + favorites.pop
puts 'length =' + favorites.length.to_s

0 =carl
last =kiko
length =2
pop =kiko
length =1

8. Writing Your Own Methods
def sayHello
puts 'say hello to everyone!'
end
sayHello
sayHello

say hello to everyone!
say hello to everyone!

8.1 Method Parameters
def saysomething words
puts 'my words: ' + words
end
saysomething 'carl is a good boy'

my words: carl is a good boy

8.2 Local Variables
We can access the variable, but we can not screw them up.
def saysomething words
words = 'nothing'
puts 'my words: ' + words
end
words = 'carl is here'
saysomething words
puts words

my words: nothing
carl is here

8.3 Return Values
puts always returns nil. Every method has to return something, even if it's just nil.
def saysomething words
puts 'my words: ' + words
'result value'
end
words = 'carl is here'
result = saysomething words
puts result
my words: carl is here
result value

references:
http://pine.fm/LearnToProgram/?Chapter=06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值