ruby基础2

ruby条件运算符

c = (a<b) ? a : b

当a<b时取c=a,否则取c=b

使用范围运算符截取字符串

txt = "cardithea"
puts txt[0..3]
puts txt[0...3]

 

转整数to_i

转浮点数to_f

转字符串to_s

对5.5做四舍五入  5.5.round

对5.5退1     5.5.floor

对5.5进1     5.5.ceil

字符串长度 "dsadsa".length

创建字符串可以 a = String.new("dsadsa")

判断字符串是否为空  "dsadas".empty?

判断字符串包含"dsadsa".include?("dsa")

判断字符串是否相等  用==就行

数组的使用

#两种初始化方法
a = [1,2,3,4,5]
b = Array.new([1,2,3])

print a
print b

puts a.length
puts a.empty? 

puts "交集#{a & b}"
puts "并集#{a | b}"
puts "全集#{a + b}"

a = a.push(10)  #类似python的append
puts "类似python的append #{a }"
a.pop(1)  #弹出一个数
puts "弹出一个数 #{a }"
a = a.insert(1,12)  
puts "插入一个数 #{a }"
a.delete(3)
puts "删除某个数 #{a }"

哈希的使用

#两种初始化方法
a = {"a" => 1, "b" => 2, "c" => 3}
b = {"a" => 1, "b" => 2}

print a
print b

puts a.length
puts a.empty? 

puts a["a"]

#hash和array的互相转换
print a.to_a  
print a.to_a.to_h

文件相关操作

require "FileUtils"

#File.rename("a.txt","b.txt") #文件重命名
#FileUtils.cp("b.txt","c.txt") #文件复制 
#FileUtils.cp("b.txt","d.txt") #文件复制 
#File.delete("d.txt") #文件删除

#Dir.mkdir("temp") #文件夹创建
#Dir.delete("temp") #文件夹删除

#输出当前文件夹下的所有内容
dir = Dir.open("./")
for name in dir
    puts name 
end

#读取文件夹内容
f = File.open("b.txt","r") 
data = f.read

print data

时间相关

puts Time.now
puts Time.now.to_i
puts Time.now.year
puts Time.now.month
puts Time.now.day
puts Time.now.hour

迭代器的使用

5.times{
    puts "hello"
}

5.times{ |n|
    puts n
}

a = ["a","b","c","d","e"]
a.each{ |i|
    puts i
}

hashset = {"a" => 1, "b" => 2, "c" => 3}
hashset.each{ |key, value|
    puts "key:#{key}  value:#{value}"
}

排序

puts [2,5,1,1,3].sort

模块的混入

module First
    A = 1
    def greet
        puts "greet"
    end
end

module Second
    B = 2
    def self.hello()  #模块自己的方法,无法混入
        puts "hello"
    end
end

class Student
    #include First   #使用include时会把First的方法混成要实例化的类方法
    extend First   #使用extend时会把First的方法混成不需要实例化的类方法
    
    def initialize()

    end
end

######include时用########
#st = Student.new()
#puts st.greet()

######extend时用########
puts Student.greet()

 

设置下载的源

gem sources --remove https://rubygems.org/
gem sources -a https://gems.ruby-china.com/
gem sources -l

Gemfile

类似mave或者graddle,在项目文件夹下创建Gemfile,然后写入需要的依赖,然后在当前目录下输入bundle install

posted @ 2022-10-08 10:08  克莱比-Kirby  阅读(26)  评论(0)    收藏  举报