Ruby笔记一(运算符)

=begin Ruby使用一个约定来区别一个名字的用法:
  名字前面的第一个字符表明这个名字的用法。
  局部变量、方法参数和方法名称应该用一个小写字母开头或者用一个下划线开头;
  全局变量用美元符作为前缀 $;  
  实例变量用 @ 开头;
  类变量用 @@ 开头;与全局变量和实例变量不同,类变量在使用前必须要初始化;全局变量和实例变量如果没有初始化,其值为 nil
  类名、模块名和常量应该用大写字母开头
=end
=begin Ruby的条件运算符比 Java 更加复杂 
  ==     :比较两个对象的值是否相等 ,返回 true, false
  eql?   :比较两个对象的值、类型是否相等,返回 true, false
  equal? :比较两个对象在内存中地址是否相同,返回 true, false
=end

a=1; b=1.0
puts a==b #a==b:true

a=1; b=1.0 
puts a.eql?(b) #false(a为整数型,b为浮点型)

a=1.0; b=1.0
puts a.equal?(b) #false

a=1.0; b=a
puts a.equal?(b) # true

#Ruby数据类型有数字,字符串,Array(数组),哈希表,Range(区间),Regex(正则表达式)

=begin
  数字分为整数型(1075 ,1e3),浮点型(2.4 ,7.0 ,0.99)。
  浮点型数据小数点后必须跟数字( 1.e3 不可以,1.1e3可以)。
  数字可以有前缀:0表示八进制, 0x表示十六进制, 0b表示二进制(07240x5AC4,0b11101)
=end
puts 0724   #7*8*8+2*8+4=468
puts 0x002A #42
puts 0b1101 #13

#Array(数组)的下标从0开始。Ruby的数组每个元素可以是不同的类型:[ 2.4,99,"thank you",[ a, b ,c ],78 ]

puts "#Array:"
for i in [ 2.4,99,"thank you",78 ]
  print i," "
end
print "\n"

#Range(区间):1..5 表示1,2,3,4,5
puts "#Range:" 
for i in 1..5
  print i," " #1 2 3 4 5
end
print "\n"

#1...5 表示1,2,3,4
for i in 1...5
  print i," " #1 2 3 4
end
print "\n"

#运算符
a = 1;b = 2 + 3 #a=1 ,b=5
a ,b = b ,a #a=5 ,b=1
print "a=",a,",b=",b
print "\n"

a = (b = 1 + 2) + 3 #a=6 ,b=3
print "a=",a,",b=",b #a=6 ,b=3
print "\n"

x = 0 #x=0
a,b,c = x, (x+1), (x+2#a=0 ,b=1,c=2
print "a=",a,",b=",b,",c=",c #a=0 ,b=1,c=2
print "\n"

#upto(limit) {|i| block } :Iterates block, passing in integer values from int up to and including limit.
puts "#upto(limit) {|i| block }:"  
5.upto(10) {|i| print i, " " }   #5 6 7 8 9 10
print "\n"

5.upto(10) { |i| print i if i<8#567
print "\n"

#each {|i| block}:Calls block once for each element in self, passing that element as a parameter
puts "#each {|i| block}:" 
(1..9).each {|i| print i," " if i<7#1 2 3 4 5 6
print "\n"

"a""b""c" ].each {|x| print x, "," }#a,b,c,
print "\n"

#step(limit[, step]) {|i| block }:Invokes block with the sequence of numbers starting at num, incremented by step (default 1) on each call
puts "#step(limit[, step]) {|i| block }:" 
1.step(102) { |i| print i, " " }  #1 3 5 7 9 
print "\n"

0.step(202) { |i| print i, " " if i%4==0 }  #0 4 8 12 16 20 
print "\n"

#ary << obj→ ary: Append—Pushes the given obj on to the end of this array
puts "#ary << obj -> ary"
print [ 12 ] << "c" << "d" << [ 34 ] #[1, 2, "c", "d", [3, 4]]
print "\n"

#join(sep=$,) → str :Returns a string created by converting each element of the array to a string, separated by sep.
puts "#join(sep=$,) -> str" 
print [ "a""b""c" ].join  #"abc"
print "\n"

print [ "a""b""c" ].join("-"#"a-b-c"
print "\n"
原文地址:https://www.cnblogs.com/jeriffe/p/2333074.html