字面量

字面量

字面量用于给一些基础类型赋值

类型 示例
Nil nil
Bool true,false
Integers 18, -12, 19_i64, 14_u32,64_u8
Floats 1.0, 1.0_f32, 1e10, -0.5
Char ‘a’, ’\n‘, ‘あ’
String “foo\tbar”, %(”あ“), %q(foo #{foo})
Symbol :symbol, :“foo bar”
Array [1, 2, 3], [1, 2, 3] of Int32, %w(one two three)
Array-like Set{1, 2, 3}
Hash {“foo” => 2}, {} of String => Int32
Hash-like MyType{“foo” => ”bar“}
Range 1..9, 1…10, 0..var
Regex /(foo)?bar/, /foo #{foo}/imx, %r(foo/)
Tuple {1, “hello”, ‘x’}
NamedTuple {name: “Crystal”, year: 2011}, {”this is a key“: 1}
Proc ->(x : Int32, y : Int32) { x + y }
- Nil #代表没有值
nil

- Bool
true,false

- Integers
Int8~ Int64, UInt8~ UInt64 #支持下划线,
1 #Int32
1_i8 # Int8
1_i64 # Int64
1_u64 # UInt64
1_000_000 # 1000000

- Floats
1.0 # Float64
1.0_f32 # Float32
1_f32 # Float32
1_000_000.222_333 # 1000000.222333

- Char
使用单引号表示

- String
使用双引号表示
可以使用#{var}进行变量插值
a, b = 1, 2
"sum: #{a + b }"
如果不想使用变量插值, 可以 %q(str_val) 来定义
百分比%, %支持多种边界符(<>,[],(),||)来定义字符串, 这样的好处是当字符串是有“时,不需要转义。
%<my name is "zhukf">   => my name is "zhukf"
多行字符串
"abc
   def"   # 这种写法会返回多行字符串  =>   abc\n      def
HereDoc, 以 <<-标志字符串 开始  , 以开头为标志字符串的行结束
<<-SOME
hello
SOME.upcase # => "HELLO"
def upcase(string)
  string.upcase
end

- Symbol
symbol被当成一个不可重复的常量
:hello
:good_bye

- String
[1, 2, 3]          # => Array(Int32)
[1, "hello", 'x']  # => Array(Int32 | String | Char)
array_of_int_or_string = [1, 3, 4] of Int32 | String  # => Array(Int32 | String)
array_of_int_or_string + ["foo"]                      # => [1, 2, 3, "foo"]
空的数组必须要声明类型
[] of Int32  # => Array(Int32).new
数组类型的字面量 {1,2,344 }
可以用于任何数据类型,只要它支持 <<方法,并且构造子接受参数

- Hash
{"one" => 1, "two" => 2}
{} of Int32 => Int32 # => Hash(Int32, Int32).new

- Range
x..y # 包含y
x...y # 不包含y

- Regex
使用 /分割, 并且使用PCRE语法。
foo_or_bar = /foo|bar/
heeello    = /h(e+)llo/
integer    = /\d+/

- 元组
tuple = {1, "hello", 'x'} # Tuple(Int32, String, Char)
tuple[0]                  #=> 1       (Int32)
tuple[1]                  #=> "hello" (String)
tuple[2]                  #=> 'x'     (Char)

- NamedTuple
tuple = {name: "Crystal", year: 2011} # NamedTuple(name: String, year: Int32)
tuple[:name] # => "Crystal" (String)
tuple[:year] # => 2011      (Int32)

- Proc
可以看作是一个带有上下文的函数入口
## 不带参数的Proc
->{ 1 } # Proc(Int32)
## 带一个参数的
->(x : Int32) { x.to_s } # Proc(Int32, String)
## 带两个参数的
->(x : Int32, y : Int32) { x + y } # Proc(Int32, Int32, Int32)
## 接收一个Int32 并返回一个String类型
Proc(Int32, String)
## 不接收参数也没有返回值
Proc(Void)
## 接收两个参数(Int32和String类型) ,并返回一个Char类型
Proc(Int32, String, Char)
## 调用Proc
proc = ->(x : Int32, y : Int32) { x + y }
proc.call(1, 2) #=> 3
## 调用定义好的方法
def plus_one(x)
  x + 1
end
proc = ->plus_one(Int32)
proc.call(41) #=> 42