Ruby编程语言学习笔记1

对应Ruby编程语言第一章  
# coding:utf-8
#
Blocks and Iterators(代码块和迭代器)
#
times and upto downto是由Integer实现的迭代器
#
times {|i| block }:Iterates block int times, passing in values from zero to int - 1.
puts  " #times {|i| block }: "   
5.times do |i|
     print i,  "   "
     print  " \n "
  end
3.times{ print  " Welcome to Ruby ,Jeriffe\n "}
# upto(limit) {|i| block }:Iterates block, passing in integer values from int up to and including limit.
print " \n "
puts  " #upto(limit) {|i| block }: "  
1.upto(9){|x|  print x, "   "}
print " \n "
# downto(limit) {|i| block }:Iterates block, passing in integer values from int down to and including limit.
print " \n "
puts  " #downto(limit) {|i| block }: " 
9.downto(1){|x|  print x, "   "}
print " \n "
# 数组(及类似的”可枚举的“对象)定义了一个each迭代器
#
each {|item| block }:Calls block once for each element in self, passing that element as a parameter.
print " \n "
puts  " #each {|item| block }: "   
a=[3,2,1]
a.each{|item|  print item, '   '}
print " \n "
# 在each迭代器基础上定义的其他迭代器
print " \n "
puts  " #在each迭代器基础上定义的其他迭代器: "   
a=[1,2,3,4]
b=a.map{|item| item*item}
print b, " \n "
c=a.select{|item| item%2==0}
print c, " \n "
d=a.inject do|sum,item|
  sum+item
end
print d, " \n "
# Methods(方法)
#
方法用def关键字来定义,方法的返回值是方法最后一个被执行的表达式
def square(x)
  x*x
end
print square(5), " \n "
# Assignment(赋值)
#
除传统的=操作符赋值外,Ruby还支持并行赋值:一个表达式中出现多余一个的值和变量
puts "  并行赋值: "
x,y=1,2
print  " x= ",x, ' ,y= ',y, " \n "
x,y=y,x
print  " x= ",x, ' ,y= ',y, " \n "
# 方法返回多个值
puts " #方法返回多个值: "
def polar(x,y)
  theta=Math.atan2(y,x)
  r=Math.hypot(x,y)
  [r,theta]
end
distance,angle=polar(2,3)
print  " distance= ",distance, ' ,angle= ',angle, " \n "


转载于:https://www.cnblogs.com/jeriffe/archive/2012/06/06/2538369.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值