随笔分类 - ruby
ruby diary
摘要:http://zetcode.com/db/mysqlrubytutorial/很不错的文章
阅读全文
摘要:b = [2,5,6]b[1,0] = [8,9] # => [2,8,9,5,6] ( 注,在index=1 插入了[8,9] ) # b[1,0] = [8,9] ,用 [8,9] 替换b数字从下标 1 的元素开始的 0 个元素. b[4..4] = [1]...
阅读全文
摘要:def do_n_times(n){ i = 1 while( i#{x}" }# --->1# --->2# --->3上面是使用关键字 yeild 来调用代码块,而下面的例子,在方法定义的时候定义了一个Proc 参数( 索引到传入的块),这个 Proc 参数需放在参数列表的最后,然后在方法里...
阅读全文
摘要:def hello # A nice simple method puts "Hello World" # Suppose we want to augment it...end alias original_hello hello # Give the method a backup named...
阅读全文
摘要:step 1 download tar.gz packagestep2 unpack tar -zxvf xxx.tar.gzstep3 cd ruby2.1.1.dirstep4 .configurestep5 makestep6 sudo make installstep7 remove 1.8...
阅读全文
摘要:A server typically has more than one interface, at least one private and one public.Since all the answers here deal with this simple scenario, a cleaner way is to ask Socket for the current ip_address_list() as in:require 'socket'def my_first_private_ipv4 Socket.ip_address_list.detect{|intf|
阅读全文
摘要:#ruby数组可以容纳不同的对象,并且没有多维数组的概念#数组的定义===========a = Array.newa = Array.new(5) #创建 5个nil 元素的数组 [nil,nil,nil,nil,nil]a = Array.new(5,1) #创建5个 元素都是1的数组 [1,1,1,1,1]a = [] #创建一个空数组a = [1,"a",3,2]%w(one two three) #返回的是 ["one","two","three"]#数组小妙用: 利用数组并行赋值a,b,c,d = [1
阅读全文
摘要:class ChineseNumber Numbers = ["一","二","三","四","五","六","七","八","九","十"] attr :chinese_number def initialize(value) if Numbers.include?(value) @chinese_number = value else raise "数字不正确" end e
阅读全文
摘要:#enum 的遍历=========[1,2,3,4].all?{|i| i>=1} # 所有是否都符合条件 返回true[1,2,3,4].all?{|i| i>=2} #返回false[1,2,3,4].any?{|i| i>=2} #有任何一个符合条件 返回true[1,2,3,4].collect {|i| i+=1} #集合中的每个元素都传递调用block,运行以数组的方式返回#enum.map 是collect 方法的别名['a','b','c','d'].each_with_index{|obj,i
阅读全文
摘要:#服务器端require 'socket'server = TCPServer.new(2000) # Server bound to port 2000loop client = server.accept #wait for a client to connect client.puts "hello !" client.puts "Time is #{Time.now}" client.closeend#客户端require 'socket's = TCPSocket.new('localhost',
阅读全文
摘要:#代码块是Proc 类的实例#使用如下:def run puts "start running" yield yield puts "finish"endrun{ puts "runing" } #当代码块在一行能容纳的时候 ,一般用花括号包围i=0run do #当代码块语句多行的时候 i += 1 puts iend#代码块也能传参数def run2(arg) yield argendrun2 ("cai") {|name| puts "hello #{name}"}i=0run2 2 do
阅读全文
摘要:#由于eval 方法不会检查字符串的内容,这样很不安全#所以我们经常用 module_eval class_eval instance_eval 来动态执行字符串形式的代码class String def truncate(n) self[0,n] end for i in [5,8,10,20] module_eval "def truncate_#{i} #注意调用的时候不能吧参数换行,否则会报参数错误 truncate #{i} end" endend puts "abcdef".truncate(2) puts ...
阅读全文

浙公网安备 33010602011771号