Hello, Ruby!

由于种种原因,简书等第三方平台博客不再保证能够同步更新,欢迎移步 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。
Ruby Logo from Wikipedia

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)。

Reference

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容