`

Programming Ruby 2nd 读书笔记4

阅读更多

C10  Basic IO

 1.  输入输出基础

while line = gets
  puts(line)
end

 

如果用ruby copy.rb a.txt,那么a.txt会作为输入文件。

 

2. File的常用方法

File.open("testfile") do |file|
  file.each_byte {|ch| putc ch; print "." }
end
File.open("testfile") do |file|
  file.each_line {|line| puts "Got #{line.dump}" }
end
File.open("testfile") do |file|
  file.each_line("e") {|line| puts "Got #{ line.dump }" }
end
IO.foreach("testfile") {|line| puts line }
# read into string
str = IO.read("testfile")
str.length -> 66
str[0, 30] -> "This is line one\nThis is line "
# read into an array
arr = IO.readlines("testfile")
arr.length -> 4
arr[0] -> "This is line one\n"

 

3. StringIO

require 'stringio'

instr = StringIO.new("I think I could forget everything, \nhowever it is imporssible")
oustr = StringIO.new()
instr.each_line do |line|
  oustr.puts(line.reverse)
end

puts(oustr.string) 

 

C11 Multiple Thread

1.  线程共享变量

count = 0
threads = []
1000.times do |i|
  threads[i] = Thread.new do
    sleep(rand(0.1))
    Thread.current["mycount"] = count
    count += 1
  end
end
threads.each {|t| t.join; print t["mycount"], ", " }
puts "count = #{count}"                            

  一般情况下,你会发现最后输出的count不等于1000。如果你的机器很快,把1000改大一些。

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics