Ruby 基础语法

· 910 words · 5 min

变量

多重赋值

a,b,c = 1,2,3
a,b,*c = 1,2,3,4,5 # c == [3,4,5]
a,*b,c = 1,2,3,4,5 # b == [2,3,4]

数值交换

a,b = 1,2
a,b = b,a
p a,b # 2 \n 1

arr = [1,2]
a,b = arr
p a,b # 1 \n 2

字符串

puts 'I \n love \n ruby'
# no transfer \n default:
# "I \n love \n ruby"

puts "I \n love \n ruby"
# double quote will transfer \n:
# I 
#  love
#  ruby

puts <<eos
12
\n
34
\n
56
eos
# eos(End Of String) as start and end flag, will print:
# 12
#
#
# 34
#
#
# 56

Log

print 'a', 'b' # 默认不加换行
puts 'a', 'b' # 默认加换行
p 'a', 'b' # 默认加换行

# 开发时打印用 p,日志中使用 print 和 puts

注释

# 单行注释
# 单行注释

=begin
多行注释
多行注释
多行注释
多行注释
多行注释
=end

if else & 三元运算

a,b = 1,2

p(if a > b then 'big' else 'small' end) # "small"

p(if a > b
  then 'big'
  elsif 'small'
  else 'unknown'
  end)
# "small"

return if error # return error when error occured
return if not success # return success if not success
return unless success # same with 'if not'

p(a > b ? 'big' : 'small') # "small"

Switch

a = 1
p(
case a
  when 1
  	'1'
  when 2,3
  	'2 or 3'
else
  'unknown'
end
)
# get "1"

循环

# times,一般单行用 {},多行用 do...end
7.times do |i|
  p "index: #{i}"
end

7.time { |i|
  p "index: #{i}"
}

# each
1..7.each do |n|
  p "current number: #{n}"
end
# 1..7 是 Range 类的一个实例

#each_with_index
arr = %w[frank, jack, david] # 或者 %w(frank jack david) 也可以
arr.each_with_index do |value, index|
  p "index: #{index}, value: #{value}"
end

# for
for i in 1..7 # do 可以省略
  p "current value: #{i}"
end

# while & until
i = 1
while i < 10
  p i
  i += 1
end
#print 1..9

j = 1
until j > 10 # until 可以认为是 while 的反面
  p j
  j += 1
end
# print 1..10

# break & next
i = 0
while i < 10
  i += 1
  if i.even?
    p 'even'
    next # same as 'continue' in JavaScript
  end
  p 'odd'
  break if i == 8
end

数组

arr = Array.new(3, Hash.new)

p arr # [{},{},{}]

Hash 散列

a = [1, 2, 3]
b = [1, 2, 3]

p a.object_id, b.object_id # 70235822548680 70235822548520
p a == b # true
p a.equal? b # false

# create a hash
peson = { name: 'david', age: 18} # 语法糖

# 相当于
person = { :name => 'david', :age => 18 }
person.keys # [:name, :age] # 其 key 是 Symbol,不是字符串

# 使用字符串作为 key,使用以下方式
person = { 'name': david, 'age': 18 }
person.keys # ["name", "age"]

# Symbol 可认为是轻量级的 String,功能更少
p :name.to_s # "name"
p 'name'.to_sym # :name

# 遍历散列
person.each do |key, value|
  p "#{key} #{value}" # Symbol key 会自动被转为 String
end

# 获取属性
person.name # error: undefined 'name' method
person['name'] # nil
person[:name] # "david"

# :name 和 'name' 是不同的
person = { :name => 'david', :age => 18 }
person['name'] = 'frank'
p person # { :name => "david", :age => 18, "name" => "frank" }

# 属性赋值为函数时
def fn
  p 1
end

person[:fn] = fn # 这里 fn 相当于 fn(),返回值为 1
person[:fn].call # error
p person # { :name => "david", :age => 18, "name" => "frank", :fn => 1 }

# 应该使用 lambda 表达式进行赋值
person[:fn] = lambda { p 1 }
# lambda 可以简写为 ->,即 person[:fn] = -> { p 1 }
person[:fn].call # 1
Ruby