Ruby学习笔记

创建固定长度初始化值的数组

arr = Array.new(26, 0)

拷贝一份数组

arr2 = arr1.dup

字符转ASCII值,不仅仅是ASCII,其他编码也行

‘a’.ord  ==> 97
97.chr  ==> ‘a'

字符串去除首尾空格:strip,去除左边空格:lstrip,去除右边空格:rstrip

读文件每一行:

File.foreach(“filename”) do |line|
end

写文件:

File.write(“filename”, “text”, {mode: “a”})
File.open(yourfile, 'w') { |file| file.write("your text") }

在irb里面输入help,然后输Class#method,如String#strip,能查看文档

gem,修改source:

gem sources --remove https://rubygems.org/
gem sources -a https://ruby.taobao.org/
gem sources -l

获取当前脚本的绝对路径

require ‘pathname’
Pathname.new(File.dirname(__FILE__)).realpath

数组随机取一个元素: arr.sample

<=> Combined comparison operator. Returns 0 if first operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second. (a <=> b) returns -1. === Used to test equality within a when clause of a case statement. (1...10) === 5 returns true. .eql? True if the receiver and argument have both the same type and equal values. 1 == 1.0 returns true, but 1.eql?(1.0) is false. equal? True if the receiver and argument have the same object id. if aObj is duplicate of bObj then aObj == bObj is true, a.equal?bObj is false but a.equal?aObj is true.

在一个子shell里面执行命令: system(“echo ‘a’”)

枚举是这样写的:

module RedisDb
    # 默认
    DEFAULT = 0
    # 倒排索引
    INVERSE_INDEX = 1
    # 问题标题缓存
    QUESTION = 2
    # 神答案缓存
    ANSWER = 3
  end

去掉字符串的空格

str.gsub(/\s+/, ‘')
str.strip()