隐式显式类型转换

Python019

隐式显式类型转换,第1张

显式的类型转换我们都知道,比如to_a、to_s、to_i方法,显示转化一般用于这样的情形: 源类型和目标类型很大程度上不相关或毫无关联

那么,隐式类型转换是什么呢?

隐式类型转换适用于源类型和目标类型很详尽的情形

ruby核心库和标准库大量使用了隐式类型转换,标准类型转换方法如下:

注:隐式、显式方法目标类都已实现

有了这些方法,我们的有些参数检查就不必使用,可以使用隐式方法代替参数检查

eg

一些首字母大写的强制类型转换方法会调用 这些隐式转换方法,如:Array(),Integer(),String()等,但是这些方法处理逻辑并不一致,有的会有限调用隐式方法、无隐式方法时再调用显式方法,有的是直接调用显式方法;具体情况还要看ruby官网文档

eg:

Ruby 程序中,命令行使用 ARGV 这个 Ruby 预定义好的数组来获取从命令行传递过来的数据。

print_argv.rb

执行 print_argv.rb 文件

从参数里得到的数据都是字符串,因此如果希望进行运算时,需要对获得的数据进行类型转换。把字符串转换为整数,我们可以使用 to_i 方法。

make[2]: Leaving directory `/data/apps/sa_gitlab/temp/ruby-1.9.3-p392/ext/objspace'

make[2]: Entering directory `/data/apps/sa_gitlab/temp/ruby-1.9.3-p392/ext/openssl'

compiling ossl_pkey_ec.c

ossl_pkey_ec.c: 在函数‘ossl_ec_group_initialize’中:

ossl_pkey_ec.c:761: 警告:隐式声明函数‘EC_GF2m_simple_method’

ossl_pkey_ec.c:761: 警告:赋值时将整数赋给指针,未作类型转换

ossl_pkey_ec.c:816: 错误:‘EC_GROUP_new_curve_GF2m’未声明(在此函数内第一次使用)

ossl_pkey_ec.c:816: 错误:(即使在一个函数内多次出现,每个未声明的标识符在其

ossl_pkey_ec.c:816: 错误:所在的函数内也只报告一次。)

make[2]: *** [ossl_pkey_ec.o] 错误 1

make[2]: Leaving directory `/data/apps/sa_gitlab/temp/ruby-1.9.3-p392/ext/openssl'

make[1]: *** [ext/openssl/all] 错误 2

make[1]: Leaving directory `/data/apps/sa_gitlab/temp/ruby-1.9.3-p392'

make: *** [build-ext] 错误 2