第一个ruby
class Player
def initialize(name="Koma")
@name=name
end
def show()
puts"player:#{@name}"
end
end
koma=Player.new()
koma.show()
bobo=Player.new("bobo")
bobo.show()
if的使用
puts"请输入第一个边的长度"
input=gets.to_i
puts"请输入第2个边的长度"
input2=gets.to_i
puts"请输入第3个边的长度"
input3=gets.to_i
if input3>input+input2
puts"这是一个三角形"
puts"三边长度分别为#{input} #{input2} #{input3}"
else
puts"这不是一个三角形"
end
case的使用:
input=gets.to_i
case input
when 1..2
puts"我猜你输入的是1或者2"
when 3..100
puts"绝对大于2"
end
while的使用:
input=gets.to_i
while input==1
puts"我猜的输入的是1"
break
end
while input!=1
puts"我猜不透你的心"
break
end
从1加到5000
sum=0
(1..5000).each { |i|
sum+=i
}
puts sum
异常处理:
a=100
while true
b=gets.to_i
begin
puts a/b
rescue StandardError => e
puts"请不要输入0"
end
end
定义函数带默认值:cmd导入才能调用
irb
require 'D:\Ruby\rubyproject\function.rb'
def add(a=0,b=0)
return a+b
end
构造函数:
class Students
def initialize(name,num,gender)
@name = name
@num = num
@gender = gender
end
end
创建对象:
a=Students.new(c参数,参数,参数)
a.sayHi
getter和setter方法:
class Students
attr_accessor :name
attr_reader :num
attr_writer :gender
def initialize(name,num,gender)
@name = name
@num = num
@gender = gender
end
end
调用常量:
Student::Version
继承:
class UniversityStudents < Students
扩充类:
把类在写一次
+def方法就行
模块相当于一个类
想要用模块里的东西:include
moudle A
PI=3.1415926
def self.sqrt(num)
Math.sqrt(num)
end
def hello
p "hello"
end
end
#调用
class Student
include A
def initialize(num)
@num=num
end
end
d第一个ruby程序:windows下不要前两行,shell下加上前两行
#!/usr/bin/ruby
# filename : first-ruby.rb
class Sample
def hello
puts "hello world "
end
end
s=Sample.new()
s.hello
第一个ruby程序:
class Sample
def hello(bobo)
puts "我是#{bobo}"
end
end
s=Sample.new()
s.hello("lele")
ruby取字符串:命令行irb
irb(main):017:0> string = "Ruby in 30 Minutes at yiibai.com"
=> "Ruby in 30 Minutes at yiibai.com"
irb(main):018:0> string[0..8]
=> "Ruby in 3"
irb(main):019:0> string[8..16]
=> "30 Minute"
irb(main):020:0> string[8..-1]
=> "30 Minutes at yiibai.com"
irb(main):021:0> string[8..-2]
=> "30 Minutes at yiibai.co"
irb(main):022:0>
字符串长度:
string.length
句子分解:可任意指定断开符号:默认找空格
C:\Users\Administrator>irb
irb(main):001:0> string = "This is my sample sentence."
=> "This is my sample sentence."
irb(main):002:0> string.split
=> ["This", "is", "my", "sample", "sentence."]
irb(main):003:0>
按特定字符分句numbers.split(" ")这里按空格分解
替换指定字符: .sub
和.gsub全部替换
irb(main):013:0> greeting = "Hello, Hello Everyone!"
=> "Hello, Hello Everyone!"
irb(main):014:0> greeting.sub("Hello","Hi")
=> "Hi, Hello Everyone!"
irb(main):015:0> greeting.gsub("Hello","Hi")
=> "Hi, Hi Everyone!"
irb(main):016:0>
自定义变量插入:
irb(main):025:0> modifier = "very "
=> "very "
irb(main):026:0> mood = "excited"
=> "excited"
irb(main):028:0> puts "I am #{modifier * 3 + mood} for today's play!"
I am very very very excited for today's play!
=> nil
irb(main):029:0>
循环重复执行5次:
class Chongfu
def zhixing
5.times do
puts "hello world"
end
end
end
s=Chongfu.new()
s.zhixing
5.times do |i| puts "#{i}: Hello, World!" end
找到并用大写替换:
irb(main):048:0> "this is a sentence".gsub("e"){|letter| letter.upcase}
=> "this is a sEntEncE"
irb(main):049:0>
用铲子工具添加元素到数组末尾:
meals << "Dessert"
irb(main):049:0> meals = ["Breakfast", "Lunch", "Dinner"]
=> ["Breakfast", "Lunch", "Dinner"]
irb(main):050:0> meals << "Dessert"
=> ["Breakfast", "Lunch", "Dinner", "Dessert"]
irb(main):051:0> meals[2]
=> "Dinner"
irb(main):052:0> meals.last
=> "Dessert"
irb(main):053:0>
数组和数字的排序:
英文字母默认按照asscii排序
irb(main):056:0> array1 = ["this", "is", "an", "array"]
=> ["this", "is", "an", "array"]
irb(main):057:0> array1.sort
=> ["an", "array", "is", "this"]
irb(main):058:0> array1
=> ["this", "is", "an", "array"]
irb(main):059:0>
哈希值-----键值对的用法;
irb(main):001:0> produce = {"apples" => 3, "oranges" => 1, "carrots" => 12}
=> {"apples"=>3, "oranges"=>1, "carrots"=>12}
<e are #{produce['oranges']} oranges in the fridge."
There are 1 oranges in the fridge.
=> nil
irb(main):003:0>
通过键值对取值:
keys---------------- values
irb(main):006:0> produce["grapes"] = 219
=> 219
irb(main):007:0> produce
=> {"grapes"=>219}
irb(main):008:0> produce["oranges"] = 66
=> 66
irb(main):009:0> produce
=> {"grapes"=>219, "oranges"=>66}
irb(main):010:0> produce.keys
=> ["grapes", "oranges"]
irb(main):011:0> produce.values
=> [219, 66]
irb(main):012:0>
键值对的简化:
irb(main):012:0> produce = {apples: 3, oranges: 1, carrots: 12}
=> {:apples=>3, :oranges=>1, :carrots=>12}
irb(main):013:0> puts "There are #{produce[:oranges]} oranges in the fridge."
There are 1 oranges in the fridge.
=> nil
irb(main):014:0>
在类的内部,通常使用def
关键字定义一个或多个方法,如下:
class Student
attr_accessor :first_name, :last_name, :primary_phone_number
def introduction
puts "Hi, I'm #{first_name}!"
end
end
当定义一个类后,还要创建类的一个实例,如下所示:
frank = Student.new
完整代码:
class Student
attr_accessor :first_name, :last_name, :primary_phone_number
def introduction
puts "Hi, I'm #{first_name}!"
end
end
frank = Student.new
frank.first_name = "Max"
frank.introduction
文件相关的处理:
在哪里用的cmd进入的irb的ruby文件就默认保存在哪里
通过Dir.pwd查看当前所在位置:
irb(main):002:0> Dir.pwd
=> "D:/Ruby/copy"
irb(main):003:0> File.rename("1.txt","2.txt")
=> 0
irb(main):004:0>
文件的重命名:返回值为0代表运行成功
irb(main):003:0> File.rename("1.txt","2.txt")
=> 0
irb(main):004:0>
文件的复制:要调用模块
require "FileUtils"
模块中中有个cp的方法:
FileUtils.cp("2.txt","3.txt")
删除文件----彻底删除,谨慎操作!!!!!!
FileUtils.delete("2.txt")
文件夹的操作:
打开文件夹:
Dir.open("../rubyproject")
读取文件名:
irb(main):016:0> dir=Dir.open("../rubyproject")
=> #<Dir:../rubyproject>
irb(main):017:1* while file_name=dir.read
irb(main):018:1* p.file_name
irb(main):019:0> end
创建文件夹:
irb(main):020:0> Dir.mkdir("temp")
=> 0
删除文件夹:
Dir.delete("temp")
时间类:初始化时间
irb(main):021:0> Time.new
=> 2022-03-06 22:20:30.4597542 +0800
获取现在的时间:
irb(main):022:0> Time.now
=> 2022-03-06 22:21:30.1456633 +0800
获取年月日时分秒:
irb(main):024:0> t.year
=> 2022
irb(main):025:0> t.month
=> 3
irb(main):026:0> t.day
=> 6
irb(main):027:0> t.sec
=> 9
irb(main):028:0>
今天是第多少天:
irb(main):028:0> t.yday
=> 65
自定义时间格式:
irb(main):030:0> Time.new.strftime("%Y%m%d %H:%M:%S")
=> "20220306 22:30:08"
irb(main):031:0>
迭代器:
5.times{|n|
p "hello"
p n
}
a=[1,2,3,4,5]
a.each{ |n|
p n}
正序和逆序排序:
a=[6,7,5,8,5,]
p r=a.sort
p r.reverse
自定义迭代器:
class Book
attr_accessor :title, :author, :
def initialize(title, author)
@title=title
@author=author
end
end
class BookList
attr_accessor :booklist
def initialize()
@booklist=Array.new(10) { |i| }
end
def add(book)
@booklist.push(book)
end
def length
@booklist.length
end
def [](n)
@booklist[n]
end
def []=(n,book)
@booklist[n]=book
end
def delete(book)
@booklist.delete(book)
end
def each_title
@booklist.each{|book|
yield(book.title)
}
end
BookList.new.each_title{|title|
p title
}
判断奇偶数:
irb(main):013:0> 3.even?
=> false
irb(main):014:0> 3.odd?
=> true
irb(main):015:0>
一个内容打印多遍:
irb(main):015:0> 3.times {p "hello"}
"hello"
"hello"
"hello"
=> 3
irb(main):016:0>
保留多少位小数点:
irb(main):016:0> 3.2333333.round(3)
=> 3.233
irb(main):017:0>
倒叙排序:
irb(main):030:0> "asdfghkuygjnbkjhskjsdhkajsd".reverse
=> "dsjakhdsjkshjkbnjgyukhgfdsa"
包含某个字符吗?
irb(main):034:0> "hello".include?('o')
=> true
查看字母的索引:
irb(main):035:0> "hello".index("o")
=> 4
irb(main):036:0>
替换某个字符:cha
irb(main):036:0> "asdf".sub("s","v")
=> "avdf"
irb(main):037:0>
查看字符长度:,转换字符为symol
irb(main):037:0> a.size
=> 4
irb(main):038:0> a.to_s
=> "asdf"
irb(main):039:0> a.to_sym
=> :asdf
irb(main):040:0>
生成数组:
irb(main):051:0> a=Array.new
=> []
irb(main):052:0> a=Array.new(3)
=> [nil, nil, nil]
irb(main):053:0>
irb(main):053:0> a=Array.new(3,0)
=> [0, 0, 0]
irb(main):054:0>
注意两种方式的区别:
irb(main):054:0> a=Array.new(3,"asdf")
=> ["asdf", "asdf", "asdf"]
irb(main):055:0> a=Array.new(3){"asdf"}
=> ["asdf", "asdf", "asdf"]
irb(main):056:0> a[0].object_id
=> 527240
比较方便的写法:
irb(main):059:0> arr=%w(foo bat hsh ksajdk sakdjs)
=> ["foo", "bat", "hsh", "ksajdk", "sakdjs"]
irb(main):060:0>
比较安全的用法:数组的取值
irb(main):059:0> arr=%w(foo bat hsh ksajdk sakdjs)
=> ["foo", "bat", "hsh", "ksajdk", "sakdjs"]
irb(main):060:0> arr[0]
=> "foo"
irb(main):061:0> arr[-1]
=> "sakdjs"
irb(main):062:0> arr[1..3]
=> ["bat", "hsh", "ksajdk"]
irb(main):063:0> arr.fetch(0)
=> "foo"
取特定值,没有就写入默认值:
irb(main):065:0> arr.fetch(5,"trsradfs")
=> "trsradfs"
数字组长度:
arr.length
存在某个特定的字符吗?
irb(main):067:0> arr.include?("sr")
=> false
array是空的,吗?
irb(main):068:0> arr.empty?
=> false
添加元素:
irb(main):069:0> arr.push("dsajkhdkjasasfkjasi")
=> ["foo", "bat", "hsh", "ksajdk", "sakdjs", "dsajkhdkjasasfkjasi"]
irb(main):070:0>
数组远处填充:
irb(main):070:0> arr[15]="ghsdhfhs"
=> "ghsdhfhs"
irb(main):071:0> arr
=>
["foo",
"bat",
"hsh",
"ksajdk",
"sakdjs",
"dsajkhdkjasasfkjasi",
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
"ghsdhfhs"]
删除特定元素:
irb(main):072:0> arr.delete_at(0)
=> "foo"
irb(main):073:0>
通过内容删除:
arr.delete("XXXX")
不显示相同的值:
irb(main):076:0> arr.uniq
=> ["bat", "hsh", "ksajdk", "sakdjs", "dsajkhdkjasasfkjasi", nil, "ghsdhfhs", "ss"]
irb(main):077:0>
随机调换元素位置:
irb(main):077:0> arr.shuffle
=>
展平多维数组:
irb(main):078:0> arr.flatten
=>
数组元素的枚举:
irb(main):083:0> arr=[1,-1,2,-3,4,2]
=> [1, -1, 2, -3, 4, 2]
irb(main):084:0> arr.each{|e| p e}
1
-1
2
-3
4
2
=> [1, -1, 2, -3, 4, 2]
irb(main):085:0>
倒着遍历:
irb(main):085:0> arr.reverse_each{|e| p e}
2
4
-3
2
-1
1
=> [1, -1, 2, -3, 4, 2]
irb(main):086:0>
带索引遍历:
irb(main):087:0> arr.each_with_index{|w , e| p [w,e]}
[1, 0]
[-1, 1]
[2, 2]
[-3, 3]
[4, 4]
[2, 5]
=> [1, -1, 2, -3, 4, 2]
irb(main):088:0>
s数组的排序:
irb(main):089:0> arr.sort
=> [-3, -1, 1, 2, 2, 4]
irb(main):090:0>
找出数组大于0 的元素:
irb(main):091:0> arr.select{|w| p w>0}
true
false
true
false
true
true
=> [1, 2, 4, 2]
irb(main):092:0>
加上和去掉nil:
irb(main):092:0> arr<<nil
=> [1, -1, 2, -3, 4, 2, nil]
irb(main):093:0> arr.compact
=> [1, -1, 2, -3, 4, 2]
irb(main):094:0>
如何定义一个hash:
irb(main):098:0> h={a:3,j:4}
=> {:a=>3, :j=>4}
irb(main):099:0>
irb(main):099:0> h={"b":3,"d":4}
=> {:b=>3, :d=>4}
irb(main):100:0>
定义hash的初始值:
irb(main):100:0> Hash.new
=> {}
irb(main):101:0> Hash.new(3)
=> {}
irb(main):102:0> h=Hash.new(3)
=> {}
irb(main):103:0> h[0]
=> 3
irb(main):104:0> h[1]
=> 3
irb(main):105:0>
HashNew([])
k=Hash.new{|h,k| h[k]=[]}
=> {}
irb(main):108:0> l=Hash.new([])
=> {}
irb(main):109:0> l[:b]<<1
=> [1]
irb(main):110:0> l[:a]<<1
=> [1, 1]
irb(main):111:0>
irb(main):112:0> k=Hash.new{|h,k| h[k]=[]}
=> {}
irb(main):113:0> k[:a]<<1
=> [1]
irb(main):114:0> k[:b]1
同时取出Key和value:
irb(main):134:0> l.assoc(:a)
=> nil
irb(main):135:0>
列表里有某个元素吗:
irb(main):135:0> l.has_value?(2)
=> false
irb(main):136:0>
拿到所有Hash的可以和value:
irb(main):137:0> k.keys
=> [:a, :b]
irb(main):138:0> k.values
=> [[1], []]
irb(main):139:0>
把两个hash合并到一起:
irb(main):139:0> h.merge(k)
=> {:a=>[1], :b=>[]}
irb(main):140:0>
遍历key和value:
irb(main):152:0> p.each{|key, value| p key,value}
:a
[1]
:b
[9]
=> {:a=>[1], :b=>[9]}
irb(main):153:0>
起别名:
irb(main):163:1* def foo
irb(main):164:1* puts "foo"
irb(main):165:0> end
=> :foo
irb(main):166:0> foo
foo
=> nil
irb(main):167:0> alias :bar :foo
=> nil
irb(main):168:0> bar
foo
=> nil
irb(main):169:0>
自定义算数方法:
运算符的重新定义
irb(main):178:0> arr=[1,2,3]
=> [1, 2, 3]
irb(main):179:1* def arr.+(num)
irb(main):180:1* self.dup<<num
irb(main):181:0> end
=> :+
irb(main):182:0> arr+4
=> [1, 2, 3, 4]
irb(main):183:0>
参数:函数定义:
irb(main):197:0> bar(a: 2,b: 5)
:a
2
:b
5
=> {:a=>2, :b=>5}
irb(main):198:0>
yield的使用:
def foo(a=2)
yield a
end
foo(4) {|a| p a}
load "XXXX.rb"
判断字符在不在前一个字符里:
def start_wtith(arr,str)
arr.each do |el|
yield el if el.start_wtith?(str)
end
end
定义一个类:
class Point
def initiable(x,y)
@x,@y =x, y
end
end
用法:
irb
load "lei.rb"
irb(main):007:0> Point.new(2,5)
=> #<Point:0x0000028aa1133840 @x=2, @y=5>
irb(main):008:0>
类方法和实例方法:
class Point
attr_accessor :x#getter setter
attr_reader :y#reader
def initialize(x=0,y=0)
@x,@y =x, y
end
def first_quadrant?
x>0&&y>0
end
def +(p2)
Point.new(x+p2.x,y+p2.y)
end
def self.second_quadrant?(x,y)
x<0&&y>0
end
class << self
def foo
end
def bar
end
def wat
end
end
end
继承:
class Point3D<Point
def initialize(x=0,y=0,z=0)
@x,@y,@z = x,y,z
end
end
按行读取文件:
改变文件夹:Dir.chdir("路径")
最简洁的:会自动关闭文件
File.readlines("path.file")
irb(main):262:0> File.readlines("D:\\Ruby\\rubyproject\\bobo.txt","r+")
=> ["123\n12345\n1234567"]
irb(main):255:1* File.open("D:\\Ruby\\rubyproject\\bobo.txt","r+") do |f|
irb(main):256:2* while line=f.gets
irb(main):257:2* puts line
irb(main):258:1* end
irb(main):259:0> end
123
12345
1234567
=> nil
写入文件:
irb(main):265:1* File.open("D:\\Ruby\\rubyproject\\bobo.txt","w+") do |f|
irb(main):266:1* f<<"hello"
irb(main):267:1* f<<"world"
irb(main):268:1* f.puts "hello"
irb(main):269:1* f.puts "word"
irb(main):270:0> end
=> nil