可以直接把某些方法定义在module Kernel中以便于在任何类里使用。
1. 浮点数保留小数点后指定位数
module Kernel def decimal_format(origin = 0, width = 1) return format("%.#{width}f", origin.to_f).to_f end end
示例:print decimal_format(123.4567, 2) # => 123.46
2. 对于数字转字符串,用0在前面补齐所需的位数
def zero_front_fix(origin = "1", bit = 2) # return sprintf("%0#{bit}d", origin.to_i) front = "" (bit-origin.length).times do front += "0" end return front + origin.to_s end
def zero_front_fix(origin = "1", bit = 3) front = "" origin = origin.to_s length = origin.length if length < bit front = "0" * (bit - length) end return front + origin end
示例:print zero_front_fix("123", 5) # => "00123"
3. 支持使用Range指定范围的随机数 by 66rpg 晴岚
module Kernel alias oldrand rand unless defined?(oldrand) def rand(thing = 0) case thing when Range oldrand(thing.end - thing.begin + (thing.exclude_end? ? 0 : 1)) + thing.begin else oldrand(thing) end end end
示例:print rand(2..10) # => 7
4. 方便使用哈希表的小方法
class Hash def assign(key, default = nil) return (self.has_key?(key) ? self[key] : default) end end
说明:传入一个主键和一个默认值参数,若该哈希表存在指定主键则返回其对应的元素,否则返回给定的默认值
示例:score = @player.assign(:score, 0)
5. 简单判断RGSS的版本,脚本通用化时可用
def rgss_version if defined? $TEST return 3 if RUBY_VERSION == "1.9.2" return 2 else return 1 end end
说明:仅有VA定义了RUBY_VERSION这一常量,而VX开始用$TEST代替了XP的$DEBUG
6. 一行脚本解决UTF-8 BOM问题 by 66rpg 英顺的马甲
File.open("test.txt","rb"){|f|p [f.read.unpack("H*").first.sub(/fffe/,"")].pack("H*")}
7. 只在 debug 模式下输出 p(by 66rpg guoxiaomi)
module Kernel alias _debug_p p def p(*args) _debug_p(*args) if $DEBUG end end
说明:请留意$DEBUG是XP的标志,VX/VA请改为$TEST
以上,2017.09.14更新