#in ruby print can be use print or puts
print "#in ruby print can be use print or puts"
puts "#in ruby print can be use print or puts"
p "#in ruby print can be use print or puts"
#these three methods all the same
#but p will auto add newline
n_0 = 150
#multiple
n_1 = n_0*9
#divide
n_2 = n_0/15
#subtract
n_3 = n_0-n_2
#addition
n_4 = n_0+n_2
#power
n_5 = n_4**3
#sqrt
n_6 = Math.sqrt(n_5)
#slice
n_7 = 15[0..]
#向上取整
25.round(-1, half: :up) # => 30
(-25).round(-1, half: :up) # => -30
# 向下取整
25.round(-1, half: :down) # => 20
(-25).round(-1, half: :down) # => -20
#Round up 向上取整
n_8 = 1.25.ceil(0)
#Round floor
n_9 = 1.66514.floor() # 向下取整
# n_9 = 1.66514.floor(1) # 保留一位数
# n_9 = 1.66514.floor(2) # 保留两位数
#integer to character and char to integer
p 122.chr #“z”
p 'a'.ord #97
p "n_1 = #{n_1}"
p "n_2 = #{n_2}"
p "n_3 = #{n_3}"
p "n_4 = #{n_4}"
p "n_5 = #{n_5}"
p "n_6 = #{n_6}"
p "n_7 = #{n_7}"
p "n_8 = #{n_8}"
p "n_9 = #{n_9}"
12345.digits # => [5, 4, 3, 2, 1]
p 55.digits(2) # 转换为二进制 [1, 1, 1, 0, 1, 1]
p 50.divmod(3) #余数 array
# Returns the greatest common divisor of the two integers. The result is always positive. 0.gcd(x) and x.gcd(0) return x.abs.
36.gcd(60) #=> 12
2.gcd(2) #=> 2
3.gcd(-7) #=> 1
# Returns an array with the greatest common divisor and the least common multiple of the two integers, [gcd, lcm].
36.gcdlcm(60) #=> [12, 180]
2.gcdlcm(2) #=> [2, 2]
3.gcdlcm(-7) #=> [1, 21]
# Returns the least common multiple of the two integers.
36.lcm(60) #=> 180
2.lcm(2) #=> 2
3.lcm(-7) #=> 21
#余数
11.remainder(4) # => 3
#int to float
1.to_f # => 1.0
#float to int
p 1.5.to_i # => 1
#进制转换
12345.to_s # => "12345"
12345.to_s(2) # => "11000000111001"
12345.to_s(8) # => "30071"
12345.to_s(10) # => "12345"
12345.to_s(16) # => "3039"
12345.to_s(36) # => "9ix"
78546939656932.to_s(36) # => "rubyrules"
sprintf("%X", ~0x1122334455) #=> "..FEEDDCCBBAA"
p rand
def rand_by_range(min, max)
return (rand * (max - min + 1)).floor + min;
end
p rand_by_range(15,20) #generates random integer at range (>=15 and <=20)
p self.rand_by_range(1,20)
p self # main
#new string
s_00 = String.new
p s_00 # ""
p s_00.encoding # #<Encoding:ASCII-8BIT>
#set encoding
s_01 = String.new("string",encoding: 'ASCII')
p s_01
#set encoding and capacity
s_02 = String.new('hello', encoding: 'UTF-8', capacity: 25)
p s_02
# string % object → new_string
#number prepend with spaces if length is not 10
s_03 = "%#10d" % 123
s_03 = "%010d" % 123 #prepend with 0
s_03 = "% 10d" % 123 #prepend with spaces
p s_03
#string * integer → new_string
s_04 ="this "*4
p s_04 # "this this this this "
# difine some string
name = "Andrew Ryan"
print "#{name}\n"
# as_bytes
s_0 = "hello"
s_0_arr = s_0.bytes
print "string to bytes:#{s_0_arr}\n"
#concat two string
s_1 = "s1"
s_2 = "s2"
s_3 = s_1+s_2
print "#{s_3}\n"
#concat string and number or number to string
n_0 = 153
ns = "#{s_1}#{n_0}"
print "string and num:#{ns}\n"
#length of string
s_4 = "this is a string"
s_4_len = s_4.length
print s_4_len
#include or contains in ruby string
s_5 = "this is a string"
s_5_h = s_5.include? "a"
p s_5_h
# string to uppercase
p "my string".yield_self {|s| s.upcase } #=> "MY STRING"
#parse string to integer
s_6 = "100"
p s_6.to_i
#parse string to floating point
p s_6.to_f
#for earch
['toast', 'cheese', 'wine'].each { |food| p "#{food.capitalize}" }
# enumerate
['toast', 'cheese', 'wine'].each_with_index do |food, index| p "#{index}:#{food}"end
arr = Array.new #=> []
5.times {|i| arr.push(i) }
p arr
arr1 = []
5.upto(10) {|i| arr1<< i } #5..=10
p arr1
Array.new(4) {Hash.new} #=> [{}, {}, {}, {}]
Array.new(4) {|i| i.to_s } #=> ["0", "1", "2", "3"]
empty_table = Array.new(3) {Array.new(3)}
#=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
Array({:a => "a", :b => "b"}) #=> [[:a, "a"], [:b, "b"]]
arr = [1, 2, 3, 4, 5, 6]
arr[2] #=> 3
arr[100] #=> nil
arr[-3] #=> 4
arr[2, 3] #=> [3, 4, 5]
arr[1..4] #=> [2, 3, 4, 5]
arr[1..-3] #=> [2, 3, 4]
arr.at(0) #=> 1
arr.first #=> 1
arr.last #=> 6
arr.take(3) #=> [1, 2, 3]
arr.drop(3) #=> [4, 5, 6]
browsers = ['Chrome', 'Firefox', 'Safari', 'Opera', 'IE']
browsers.length #=> 5
browsers.count #=> 5
browsers.include?('Konqueror') #=> false
arr = [1, 2, 3, 4]
arr.push(5) #=> [1, 2, 3, 4, 5]
arr << 6 #=> [1, 2, 3, 4, 5, 6]
#push front
arr.unshift(0) #=> [0, 1, 2, 3, 4, 5, 6]
arr.insert(3, 'orange', 'pear', 'grapefruit')
#=> [0, 1, 2, "orange", "pear", "grapefruit", "apple", 3, 4, 5, 6]
arr = [1, 2, 3, 4, 5, 6]
arr.pop #=> 6
arr.shift #=> 1
arr.delete_at(2) #=> 4
arr.delete(2) #=> delete all 2
# remove nil values
arr = ['foo', 0, nil, 'bar', 7, 'baz', nil]
arr.compact #=> ['foo', 0, 'bar', 7, 'baz']
# non-destructive uniq dedup
arr = [2, 5, 6, 556, 6, 6, 8, 9, 0, 123, 556]
arr.uniq #=> [2, 5, 6, 556, 8, 9, 0, 123]
arr = [1, 2, 3, 4, 5]
arr.each {|a| print a -= 10, " "}
# prints: -9 -8 -7 -6 -5
p ""
#reverse to string
words = %w[first second third fourth fifth sixth] #["first", "second", "third", "fourth", "fifth", "sixth"]
p words
str = ""
words.reverse_each {|word| str += "#{word} "}
p str #=> "sixth fifth fourth third second first "
#reverser
a = ['foo', 'bar', 'two']
a1 = a.reverse
arr.map {|a| 2*a} #=> [2, 4, 6, 8, 10]
p arr #=> [1, 2, 3, 4, 5]
arr = [1, 2, 3, 4, 5, 6]
arr.select {|a| a > 3} #=> [4, 5, 6]
arr.reject {|a| a < 3} #=> [3, 4, 5, 6]
arr.drop_while {|a| a < 4} #=> [4, 5, 6]
arr.delete_if {|a| a < 4} #=> [4, 5, 6]
arr.keep_if {|a| a < 4} #=> [1, 2, 3]
a = 'abcde'.split('').shuffle
a # => ["e", "b", "d", "a", "c"]
a1 = a.sort
a1 # => ["a", "b", "c", "d", "e"]
def one_plus_one
1 + 1
end
p one_plus_one
def say_goodnight(name)
"Good night, #{name.capitalize}"
end
p say_goodnight("Andrew")
class Person
def initialize(*args)
@name = args[0]
@age = args[1]
end
def name
@name
end
def age
@age
end
end
pp1 = Person.new("Andrew",26)
p pp1
p pp1.name
p pp1.age
person = Class.new do
def initialize(*args)
@name = args[0]
@age = args[1]
end
def name
@name
end
def age
@age
end
def run
p self
p self.name
p self.age
end
end
pp2 = person.new("Ryan",25)
p pp2.run
Person = Struct.new(:name, :age)
me = Person["Andrew",26]
p me
p me.name
5.times { print "Odelay!" }
=begin
#forever loop
loop do
print "Much better."
print "Ah. More space!"
print "My back was killin' me in those crab pincers."
end
=end
require 'json'
json = JSON.parse("{\"name\"=\"ansrew\"}")
p json
#read all lines
File.open("./file/demo.txt") do |f|
# f_string = f.gets #read first line
f_string = f.read
p f_string
end
#read to string array split by "\n"
File.open("./file/demo.txt") do |f|
f_arr = f.read.split("\n")
p f_arr
end
#read each line
File.foreach("./file/demo.txt") { |line| puts line }
#write to file
File.open("./file/log.txt", "w") { |f| f.write "#{Time.now} - User logged in\n" }
# ||
File.write("./file/log.txt","some data")
#append to log file
File.write("./file/log.txt", [1,2,3].join("\n"), mode: "a")
# Renaming a file
File.rename("./file/log.txt", "./file/new_log.txt")
# File size in bytes
File.size("./file/new_log.txt")
# Does this file already exist?
File.exists?("./file/new_log.txt")
# Get the file extension, this works even if the file doesn't exists
File.extname("./file/new_log.txt")
# => ".txt"
# Get the file name without the directory part
File.basename("./file/new_log.txt")
# => "new_log.txt"
# Get the path for this file, without the file name
File.dirname("./file/new_log.txt")
# => "./"
# Is this actually a file or a directory?
File.directory?("./")
#list current dir
def find_files_in_current_directory
entries = Dir.entries("./")
entries.reject { |entry| File.directory?(entry) }
end
dir_list = find_files_in_current_directory()
# p dir_list
#get the status of dir or file
File.stat("/home")
File.stat("./file/demo.txt")
# All files in current directory
dir_list = Dir.glob("*")
p dir_list
# All files containing "spec" in the name
Dir.glob("*spec*")
# All ruby files
Dir.glob("*.rb")
#get current working directory
Dir.pwd #"/home/andrew/code/jihulab/ruby_code/learn_ruby"
#is empty
Dir.empty?("/tmp")
#make dir
10.times do |i| #0..=9
Dir.mkdir("/tmp/test#{i}")
end
#is exists
Dir.exists?("/home/jesus")
require 'net/http'
Net::HTTP.start( 'blog.udemy.com', 80 ) do |http|
print( http.get( '/ruby-print/' ).body )
end
system("ls")
exec("du")
cmd = open("|date")
print cmd.gets
cmd.close