本文共 2508 字,大约阅读时间需要 8 分钟。
都说 Python 和 Ruby 长得很像,难道 Crystal 和 Ruby 就长得不像么!
安装:centos 下可以用 yum install crystal 命令进行安装(具体要配置些啥东西我也忘了,哈哈)。
参考链接: (毋庸置疑,原文这个链接比我这儿写得更好)。相同语法部分就不多说了,主要针对语法有差异的部分写一下罢了。
除了 false 和 nil 是假,其他都是真。(这个和 Ruby 是保持一致的)
# Crystal42.class #=> Int32true.class #=> Boolnil.class #=> Nil'c'.class #=> Char"hello".class #=> String[1, 2].class #=> Array(Int32){1 => 2}.class #=> Hash(Int32, Int32)class CatsendCats.class #=> Class
# Ruby[1] pry(main)> 42.class=> Integer[2] pry(main)> true.class=> TrueClass[5] pry(main)> nil.class=> NilClass[6] pry(main)> false.class=> FalseClass[7] pry(main)> "hello".class=> String[8] pry(main)> [1, 2].class=> Array[9] pry(main)> {1 => 2}.class=> Hash[3] pry(main)> class Cats[3] pry(main)* end => nil[4] pry(main)> Cats.class=> Class
crystal 是区分字符串(String)和字符(Char)的哟!字符串必须用双引号 ",字符可以用双引号也可以用单引号,但是一般规范是字符用单引号括起来。
# CrystalIn test.cr:5:6 5 | puts 'sdf' ^Error: unterminated char literal, use double quotes for stringsstring = "hello world"string.includes? "hello" #=> truestring.starts_with? "hello" #=> truestring.ends_with? "world" #=> true
# Ruby[7] pry(main)> string = "hello world"=> "hello world"[8] pry(main)> string.include? "hello"=> true[9] pry(main)> string.start_with? "hello"=> true[10] pry(main)> string.end_with? "world"=> true
# Crystalcats = [] # Syntax error in :1: for empty arrays use '[] of ElementType'cats = [] of String #=> [] : Array(String)array = [2, 3, 4, 5]array.includes? 3 #=> truecats = ["Ferguson", "Sardine"]cats[2] #=> syntax error : Unhandled exception: Index out of bounds (IndexError)cats[2]? #=> nil
# Ruby[4] pry(main)> cats = []=> [][5] pry(main)> array = [2, 3, 4, 5]=> [2, 3, 4, 5][6] pry(main)> array.include? 3=> true=> ["Ferguson", "Sardine"][5] pry(main)> cats[2]=> nil
# Crystal[root@master crystal_learning]# cat test.crFile.open("test.txt", "w") do |io| io.puts "Hello, world.\n"end[root@master crystal_learning]# crystal test.cr [root@master crystal_learning]# cat test.txtHello, world.
# Ruby[root@master ruby_learning]# cat test.rbFile.open("test.txt", "w") do |io| io.puts "Hello, world.\n"end[root@master ruby_learning]# cat test.txtHello, world.
# Crystalaa=["hello ", " world", "nice "]aa.map!(&.strip)puts aa.inspect[root@master crystal_learning]# crystal test.cr["hello", "world", "nice"]
# Rubyaa=["hello ", " world", "nice "]aa.map!(&:strip)puts aa.inspect[root@master ruby_learning]# ruby test.rb["hello", "world", "nice"]
转载地址:http://ynjqi.baihongyu.com/