由于种种原因,简书等第三方平台博客不再保证能够同步更新,欢迎移步 GitHub:https://github.com/kingcos/Perspective/。谢谢!
Date | Notes | Ruby |
---|---|---|
2018-01-06 | 首次提交:Ruby 基本语法 | 2.3.3p222(Default on macOS 10.13.2) |
为了简单了解一下 CocoaPods,所以决定了解下 Ruby 这门语言。当然,本文仅仅只是抛砖引玉,详细的文档资料还请有兴趣的同学 Google 一下。
So, talk is cheap, show me the code!
What & Why?
What is Ruby?
- Ruby,原意「红宝石」。
- 而在本文中,Ruby 特指一种面向对象的解释性编程语言。
- 关于 Ruby,这里不做过多的背景介绍,有兴趣的同学可以查阅文末的 Reference。
Why Ruby?
- Because CocoaPods & Fastlane...
Basic Grammar
- 关于「环境搭建」,由于 macOS 已经自带了 Ruby,所以这里不再赘述。
- Ruby 原生支持 REPL(Read-Eval-Print-Loop),只需要在 Terminal 输入 Interactive Ruby Shell 的简称
irb
即可,但下文仍采用ruby rubyFilename.rb
形式运行。
Hello world!
- 在 Ruby 官网,就可以直接看到这个代码段。
- 如同注释所写,Ruby 没有
main
方法,换行(puts
自带换行),以及分号。
# The famous Hello World
# Program is trivial in
# Ruby. Superfluous:
#
# * A "main" method
# * Newline
# * Semicolons
#
# Here is the Code:
puts "Hello World!"
- OUTPUT:
Hello world!
BEGIN
& END
& Comments
END {
# END 语句
puts "ENDING"
}
BEGIN {
# 另一个 BEGIN 语句
puts "Another BEGINNING"
}
# 单行注释
puts "我是谁?我在哪儿?发生了什么?"
=begin
# 块注释:
可以嵌套单行注释
但是不能嵌套块注释
=end
END {
# 另一个 END 语句
puts "Another ENDING"
}
BEGIN {
# BEGIN 语句
puts "BEGINNING"
}
- OUTPUT:
Another BEGINNING
BEGINNING
我是谁?我在哪儿?发生了什么?
Another ENDING
ENDING
Data Types
Number
-
+-*/%
类似其他语言的加减乘除取余,指数操作类似 Python,为**
。
# Integer
puts 123 # 123
puts 1_234 # 1234 (Like Swift...)
puts 0123 # Octonary
puts 0x123 # Hex
puts 0b111 # Binary
puts "---"
# Fixnum (-2^62 <= N <= 2^62 - 1)
a = 2 ** 62 - 1 # Fixnum
puts a.class
a += 1 # Bignum
puts a.class
puts "---"
puts "a".ord # "a" 的字符编码
puts "---"
# Float
b = 123.4
puts b.class
puts 5E3
puts 5E+3 == 5E3
- OUTPUT:
123
1234
83
291
7
---
Fixnum
Bignum
---
97
---
Float
5000.0
true
String
-
""
双引号的字符串比''
单引号的字符串更加灵活。
puts "str".class
lang = "Swift"
puts "A: \"Why you write #{ lang }?\"" # #{exp} only "" support
puts 'Kingcos: "Because I can."'
- OUTPUT:
String
A: "Why you write Swift?"
Kingcos: "Because I can."
Array
arr = [
2018,
"Dog Year",
2.16
]
# Iterate elements of an array
arr.each do |I|
puts I
end
- OUTPUT:
2018
Dog Year
2.16
Hash
hash = {
"Year" => 2018,
"Month" => 1,
"Day" => 6
}
# Iterate key-value pairs of a hash
hash.each do |key, value|
print key, " => ", value, "\n"
end
- OUTPUT:
Year => 2018
Month => 1
Day => 6
Range
- 仅提醒熟悉 Swift 的同学,在 Swift 中的
...
左闭右闭而在 Ruby 中是左闭右开。
range = 1 .. 5 # Included 5
range.each do |n|
print n, " "
end
puts "\n---"
(1 ... 5).each do |n|
print n, " "
end
- OUTPUT:
1 2 3 4 5
---
1 2 3 4
Classes & Objects
# Define classes
class NokiaPhone
# Access local variables easily (R+W)
attr_accessor:currency
# Class variables
@@sales = 0
# Define functions
def initialize(price, currency = "¥") # Default value
# Initializer
puts "This is the official initializer."
# Local variables
@price = price
@currency = currency
@@sales += 1
end
# Getter & setter
def getPrice
return @price
end
# Comment setter for access control
# def setPrice(price)
# @price = price
# end
# Functions with arguments
def call(phoneNumber)
print "Calling ", phoneNumber, "\n"
end
# Class functions
# def NokiaPhone.printSales
def self.printSales
puts @@sales
end
end
# Create an instance of a class
nokia1110 = NokiaPhone.new(100, "$")
# Call functions
nokia1110.call(110)
# Fetch variables
print nokia1110.getPrice, nokia1110.currency, "\n"
nokiaN97 = NokiaPhone.new(6888)
NokiaPhone.printSales
- OUTPUT:
This is the official initializer.
Calling 110
100$
This is the official initializer.
2
Determine & Loop
Determine
todayWeather = "Rainy"
# `if-then` in one line
if todayWeather == "Rainy" then puts "Take your umbrella." end
# `then` is omitted
if todayWeather == "Rainy"
puts "Take your umbrella."
end
# `if-elsif-else`
if todayWeather == "Rainy"
puts "Take your umbrella."
elsif todayWeather == "Foggy"
puts "Wear your mask."
else
puts "Enjoy your good day!"
end
# `unless`
x = 10
unless x > 2
puts "x < 2"
else
puts "x >= 2"
end
# `$` declares global variables
$debug = 1
puts "DEBUG INFO" if $debug
puts "RELEASE INFO" unless $debug
# `case` is like switch in Swift
devType = "iOS"
case devType
when "FE"
puts "HTML", "CSS", "JavaScript"
when "BE"
puts "Java", "Python", "Php", "Ruby"
when "Android"
puts "Kotlin", "Java"
when "iOS"
puts "Objective C", "Swift"
else
puts "Other programming language."
end
- OUTPUT:
Take your umbrella.
Take your umbrella.
Take your umbrella.
x >= 2
DEBUG INFO
Objective C
Swift
Loop
$sum = 0
$n = 0
# while
while $n < 5 do
$n += 1
$sum += $n
end
puts $sum
$n = 0
# until
until $n > 5 do
$n += 1
$sum += $n
end
puts $sum
# for-in
for i in 0 .. 5
print "#{ i } "
end
puts
# each
(0 .. 5).each do |I|
print "#{ i } "
end
puts
# break & next (next is like continue in Swift)
for i in 0 .. 5
if i == 2
next
elsif i == 4
break
end
print "#{ i } "
end
- OUTPUT:
15
36
0 1 2 3 4 5
0 1 2 3 4 5
0 1 3
Code Snippets
- Ruby 官网右侧的代码段不只有一个「Hello world」,以下这几段也能简单地了解 Ruby 的语法。
# Output "I love Ruby"
say = "I love Ruby"
puts say
# Output "I *LOVE* RUBY"
say['love'] = "*love*"
puts say.upcase
# Output "I *love* Ruby"
# five times
5.times { puts say }
# Ruby knows what you
# mean, even if you
# want to do math on
# an entire Array
cities = %w[ London
Oslo
Paris
Amsterdam
Berlin ]
visited = %w[Berlin Oslo]
puts "I still need " +
"to visit the " +
"following cities:",
cities - visited
# The Greeter class
class Greeter
def initialize(name)
@name = name.capitalize
end
def salute
puts "Hello #{@name}!"
end
end
# Create a new object
g = Greeter.new("world")
# Output "Hello World!"
g.salute
后记
- Ruby 也可以写后端,比较有名的是 Rails 框架(Ruby on Rails)。