Last active
December 17, 2015 08:59
-
-
Save kencharos/5584281 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def readStdIn() | |
input = [] | |
while line = gets | |
input << line.chomp | |
end | |
return input | |
end | |
# 1.9 | |
def readFile(name) | |
File.read(name, :encoding => Encoding::UTF_8).encode.split("\n") | |
end | |
#1.8 | |
def readFileOther(name) | |
input = [] | |
File.open(name, "r") {|io| | |
while line = io.gets | |
input << line | |
end | |
} | |
return input | |
end | |
#1.9.3 | |
def writeFile(name, data) | |
File.write(name, data.join("\n")) | |
end | |
#1.8 | |
def writeFileOther(name, data) | |
File.open(name, "w") {|io| | |
data.each {|line| io.puts line} | |
} | |
end | |
# string to array, array to string | |
a = "1,2,3".split(",") #[1,2,3] | |
b = a.join(":") #"1,2,3 | |
# stirng to number | |
"2".to_i | |
"2".to_f | |
# collection | |
list =[1,2,3,4,5] | |
# filter, map -> reject, map. And, ! is destory method. | |
list.reject{|e| e > 2}.map{|n| n * 2} | |
#with index | |
list.each_with_index{|e, i| p "index:#{i}, valur:#{e}"} | |
#ref to previous element | |
list.each_cons(2){|first, second| p "[#{first},#{second}]"} #{1,2], [2,3], [3,4], [4,5] | |
#grouping | |
list.each_slice(2).map{|e| e} #[[1,2], [3,4], [5]] | |
# sum, | |
list.inject{|e,i| e * i} # 120 | |
list.inject{|e,i| e + i} # 15 | |
#uniqe (set) | |
[1,2,3,4,4,4,2].uniq #[1,2,3,4] | |
#regeqp | |
# initial | |
r1 = %r([\d]{4}) | |
r2 = /[A-Z]{3}/ | |
#mathc | |
r1 === "1234" # true | |
r2 === "abc" # false | |
#with case | |
res = case "ABC" | |
when r1; "r1 hit" | |
when r2; "r2 hit" | |
else; "not hit" | |
end #r2 hit | |
# get match string | |
%r|([\d]{4})/([\d]{2})/([\d]{2})| =~ "today is 2012/01/02." | |
p $` # today is | |
p $& # 2012/01/02 | |
p $1 # 2012 | |
p $2 # 01 | |
p $3 # 02 | |
p $' # . | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment