Hello, Ruby!

2018-01-07  本文已影响51人  萌面大道

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

Why Ruby?

Basic Grammar

Hello world!

# The famous Hello World
# Program is trivial in
# Ruby. Superfluous:
#
# * A "main" method
# * Newline
# * Semicolons
#
# Here is the Code:

puts "Hello World!"
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"
}
Another BEGINNING
BEGINNING
我是谁?我在哪儿?发生了什么?
Another ENDING
ENDING

Data Types

Number

# 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
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."'
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
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
Year => 2018
Month => 1
Day => 6

Range

range = 1 .. 5 # Included 5
range.each do |n|
    print n, " "
end

puts "\n---"

(1 ... 5).each do |n|
    print n, " "
end
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
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
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
15
36
0 1 2 3 4 5
0 1 2 3 4 5
0 1 3 

Code Snippets

# 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

后记

Reference

上一篇 下一篇

猜你喜欢

热点阅读