-
Notifications
You must be signed in to change notification settings - Fork 3
/
block_sample.rb
107 lines (84 loc) · 1.56 KB
/
block_sample.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
def call_block
puts "start"
yield "foobar" if block_given?
puts "end"
end
def call_block2(&block)
puts "start"
block.call("foobar")
puts "end"
end
call_block do |str|
puts "here"
puts str
puts "here"
end
# start
# here
# foobar
# here
# end
f = File.open("myfile.txt", 'w')
f.write("Lorem ipsum dolor sit amet")
f.write("Lorem ipsum dolor sit amet")
f.close
# using block
File.open("myfile.txt", 'w') do |f|
f.write("Lorem ipsum dolor sit amet")
f.write("Lorem ipsum dolor sit amet")
end
# with code block
def send_message(msg)
connection do |socket|
socket.puts "foobar"
socket.gets
end
end
def connection
socket = TCPSocket.new(@ip, @port)
yield socket # 用块的方式把外层的参数 闭包传到块里面
ensure
socket.close
end
end
class SortedList
def initialize
@data = []
end
def <<(element)
(@data << element).sort!
end
def each
@data.each {|e| yield(e)}
end
end
File.open("some.txt"){|f| f << "some words"}
"this is a string".instance_eval do
"O hai, can has reverse? #{reverse} . "
end
foo = Hash.new{ |h,k| h[k] = []}
require 'socket'
class Client
def initialize(ip = "127.0.0.1", port = "3003")
@ip = ip
@port = port
end
def send_message(msg)
connection do |socket|
socket.puts(msg)
response = socket.gets
end
end
def receive_message
connection do |socket|
response = socket.gets
end
end
private
def connection
socket = TCPSocket.new(@ip, @port)
yield(socket)
ensure
socket.close if socket
end
end