Учебник языка Ruby

download Учебник языка Ruby

If you can't read please download the document

description

http://ru.wikibooks.org/wiki/Ruby

Transcript of Учебник языка Ruby

Ruby . , , . , . . , , , , . , , , . . , , , , . 1993 (24 ) ( ), , , . Ruby. : , . . Ruby . -, : -, .

1 Ruby 2

2.1 2.2

2.2.1 fxri:

2.2.2

2.3 2.4 2.5

2.5.1

3

3.1 3.2

3.2.1 3.2.2

3.3 3.4 3.5 3.6 3.7

4

4.1 4.2 4.3 4.4

4.4.1 4.4.2

4.5 4.6 4.7 4.8

5

5.1 5.2 5.3

5.4

5.4.1 5.4.2 / 5.4.3 5.4.4 5.4.5 / 5.4.6 ( ) 5.4.7 5.4.8 5.4.9 5.4.10 5.4.11 5.4.12 5.4.13 // 5.4.14 ,

5.5

5.5.1 ? 5.5.2 ?

5.6

5.6.1 5.6.2 5.6.3 // 5.6.4

5.7

5.7.1 ? 5.7.2 ?

5.8 5.9

5.9.1

5.9.1.1

5.9.2

5.9.2.1

6

6.1 ? 6.2

6.2.1 6.2.2 6.2.3 6.2.4 6.2.5

6.3

6.3.1 6.3.2 6.3.3 6.3.4 6.3.5 6.3.6 6.3.7 6.3.8 6.3.9 /

6.4

6.4.1 ? 6.4.2 ? 6.4.3 ?

6.5 6.6 6.7

7

7.1

7.1.1 ?

7.2

7.2.1 7.2.2 7.2.3 7.2.4 7.2.5 - 7.2.6 ! 7.2.7 7.2.8

7.2.8.1 7.2.8.2 7.2.8.3 7.2.8.4 7.2.8.5 7.2.8.6

7.2.9 7.2.10 7.2.11 7.2.12

7.3

7.3.1 7.3.2

7.4

8

8.1

8.1.1 8.1.2 8.1.3 8.1.4 8.1.5 ""

8.2

8.2.1 8.2.2 8.2.3 8.2.4 8.2.5

8.3 ,

8.3.1 .size 8.3.2

8.4

8.4.1 //? 8.4.2 -

8.5 ? 8.6 ? 8.7 ? 8.8 ?

9

9.1 ? 9.2 2- ? 9.3 ?

9.3.1

9.4 9.5 ? 9.6 9.7

9.7.1

10

10.1 IO 10.2 10.3

10.4 10.5

11

11.1 ?

11.1.1 11.1.2

11.2 ?

11.2.1 11.2.2 ERB 11.2.3 ERB- 11.2.4 ERB- ERB-

11.3 , 11.4 ? 11.5 11.6 11.7 - 11.8 HTML-

11.8.1 11.8.2

11.9 You have got mail 11.10 -

11.10.1

12 13

13.1 13.2 13.3

Ruby :

()

:

.

- :

. Class , , , , . . - ( ) , ; , Unix (, ),

:

:

( .exe- Windows)

, . , . . / . Ruby , . , . Ruby, . TecToBa9_nporpamma.rb ( .rb), Unix-e :%

ruby TecToBa9_nporpamma.rb

Windows . STDIN.getc

Windows .rbw, Windows- rubyw, . ruby . rubyw STDIN.getc

. :puts " !"

npuBeT_mup.rb . : !

.

, . irb, . %

irb

. :% irb(main):001:0> % => [1, 2, 3, 4]

[1,2,3,4]

Ruby , . , , :% irb(main):002:0> "text".methods % => ["respond_to?", "%", "index", "select", ...]

:% irb(main):002:0> % => 70

14 * 5

exit. , () , Ruby ( , ). irb , , . fxri: Windows fxri. , ri irb. fx FXRuby. ri Ruby Informer ( ). fxri : c . . irb, .

, . .

, ( ). Ruby #. , . :puts 2+2 puts "!" # #

#->. :puts 2+2 puts "" #-> 4 #->

Ruby : print, printf, p, puts, .display . :

puts. . , , puts .to_s ; p. , - . , puts, . ( ) , .inspect.

:puts [1,2,3,4] p [1,2,3,4] puts "npuBeT!" p "npuBeT!" puts 5 p 5 #-> 1\n2\n3\n4 # \n - #-> [1,2,3,4] #-> npuBeT! #-> "npuBeT!" #-> 5 #-> 5

, . , p,

, puts.

, p "\323\367\350\362\345 \320\363\341\350!"

:$KCODE = "utf-8"

utf-8 SciTE. , ( )

, . Ruby :

; , .

:maccuB nepemeHHa9 gpyra9_nepemeHHa9 HenpaBuJIbHa9_nepemeHHa9 3JIemeHT _3JIemeHT ___

# # # #

. . ,

, , . , , UTF-8, -KU (=), :maccuB = [1,2,3,4] nepemeHHa9 = maccuB + [1,2] gpyra9_nepemeHHa9 = nepemeHHa9 - maccuB

, =, , . nepemeHHa9 [1, 2, 3, 4, 1, 2], maccuB + [1, 2]. (+) : .

-:nogpyra = "" k_HAM_B_rocTu_ugeT = nogpyra puts nogpyra #-> "", k_HAM_B_rocTu_ugeT[0] = "" # ( ) - puts nogpyra #-> "" # ,

, , , . () - . , , , , , ( ). nogpyra "", :nogpyra = "" k_HAM_B_rocTu_ugeT = nogpyra.clone k_HAM_B_rocTu_ugeT[0] = "" # . : puts nogpyra #-> ""

.dup. , . , ( ) :#... k_HAM_B_rocTu_ugeT = ""; # , p nogpyra #-> ""

Ruby . : Fixnum ( , 231), Bignum ( , 231), Float ( ), Array (), String (), Hash ( ). , , . pWrapPolygonVertices8;5;(-25,0);(-25,21554);(21600,21554);(21600,0);(-25,0)wzTooltip"

"posh2fBehindDocument1fIsButton1fLayoutInCell1

Ruby :5 # # # # # #

-12 4.5 076 0b010 0x89

.

|| "" or && "" and ! "" not ^ " " xor () . Ruby true ( ) false ( ). . .

== != < > = , , =< "--, "

- , . .maccuB[0] #=> " maccuB"

, . , , .

. Ruby . :

. . . ( + []). ( .inspect .to_s ). , ( .gsub, .match, .scan, .split).

. Ruby , . Perl 6 , ;

Ruby . .

" () ' ( ). :" " ' ' # #

, , , .

. : , => - . , .{ "" => " ", 807 => " !"}

, :"npeBeg" => "MegBeg"

:puts puts puts puts puts maccuB[""] #-> maccuB["807"] #-> nil maccuB[807] #-> ! maccuB[1] #-> nil maccuB["npeBeg"]#-> MegBeg

.

, ( Range). : , ( .. ...). ( ) , , .succ. :'a'..'z' 'a'...'z' 1..100 1...100

# , 'a'..'y' # , 1..99

, .succ ( ), , . : , , .

, .succ . , ( .succ)

, . , - . , Object.str = "A " str.class #-> String str.class.superclass #-> Object

. , , . , . . .

: ( Fixnum Bignum) ( Float). , , , .

Ruby , . . 231 ( ), , . , , , . Fixnum 231 ( ), Bignum. Bignum 231, Fixnum. ( + ). , ( ): 0 , 0x , 0b . , . , . , :# Fixnum 123_456 # -567 # 0xbad #

0377 # -0b101010 # 0b0101_0101 # # Bignum 123_456_789_123_456 -123_456_789_123_456 07777777777777777777 # # #

, (Fixnum) (Bignum) .

, . (). : 0.1234e2 1234e-2 12.34.# Float -12.34 # 0.12342 # 12.34 1234-2 # 12.34

, . mathn ( ).

, . Numeric (). , , . : Integer (), Float () Complex (). Rational (), . Integer : Fixnum ( ) Bignum ( ). , 231 , .

Fixnum Bignum 231 . , , Bignum Fixnum. , mathn. Complex (). Complex () ,

Integer (Fixnum Bignum), Float ( ). mathn, Rational ().

Rational 1, Integer (Fixnum Bignum).

Ruby , : (+), (-), (*), (/), (%), (**).6 6 6 6 6 6 + 4 - 4 * 4 / 4 % 4 ** 4 #-> #-> #-> #-> #-> #-> 10 2 24 1 2 1296

, ( ). , . :2 + 2 * 2 (2 + 2) * 2 #-> 6 #-> 8

, . :1/3 2/3 3/3 #-> 0 #-> 0 #-> 1

, , , . Ruby , . , . , , .

6.0 + 4 6 - 4.0 6.0 * 4.0 6.0 / 4 6.0 % 4 6 ** 4.0

#-> #-> #-> #-> #-> #->

10.0 2.0 24.0 1.5 ( , ) 2.0 1296.0

. Ruby. try ruby!. & | ^ > ~

. .6 & 4 6 | 4 6 ^ 4 6 > 4 ~4 #-> #-> #-> #-> #-> #-> 4 6 2 96 0 ( ) -5 ( )

, , . , . :ogHo_4ucJIo += gpyroe_4ucJIo

. :

ogHo_4ucJIo = ogHo_4ucJIo + gpyroe_4ucJIo

, + , .cTpoka = "" cTpoka += ", " cTpoka *= 3 cTpoka #-> ", , , " maccuB = [1,2,3] maccuB += [4,5] maccuB #-> [1,2,3,4,5]

+, += . , .

to_f to_i to_s to_a

Ruby to_. , (f Float , i Integer , s String , a Array ). :7.to_f 7.9.to_i 7.to_s 7.to_a #-> #-> #-> #-> 7.0 7 "7" [7]

. :rand(100) rand # 86 #-> 0.599794231588021

, rand 0 99 ( 1

100). , rand 0.0 1.0 . :

( 100), ( 0...N, N ); , 0.0 1.0.

. srand. ( ). , . : , .srand 123 Array.new(5){ rand(100) }

#-> [69, 71, 28, 42, 22]

, . 123 . ! srand , .

: .ucxogHoe_4ucJIo = 1234 puts sprintf("%b",ucxogHoe_4ucJIo) # sprintf puts ucxogHoe_4ucJIo.to_s(2) # - " ", # 8 16, 5, 30...

:ucxogHoe_4ucJIo = 1234 puts ucxogHoe_4ucJIo.to_s.reverse

# reverse

N- :ucxogHoe_4ucJIo, N = 1234, 5 puts ucxogHoe_4ucJIo[ N ]

:

ucxogHoe_nepBoe, ucxogHoe_BTopoe = 134, 234 ucxogHoe_nepBoe, ucxogHoe_BTopoe = ucxogHoe_BTopoe, ucxogHoe_nepBoe puts ucxogHoe_nepBoe, ucxogHoe_BTopoe

:gpo6Hoe_4ucJIo = 3.1415926535 puts ( gpo6Hoe_4ucJIo * 100 ).to_i.to_f / 100 puts sprintf( "%.2f", gpo6Hoe_4ucJIo ).to_f

# =)

1. ? 2. ? 3. ? 4. ? (, .) 5. , 1890 . ? ?

, . ( ) .

. :[1,2,3,4,5,6]

, . . , .new Array. :Array.new( 6 ){ |index| index + 1 } #-> [1,2,3,4,5,6]

.new ( 6). , . , . Range () .to_a:

(1..6).to_a

#-> [1,2,3,4,5,6]

, .

to_a , .(1..10).to_a ('a'..'d').to_a #-> #-> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ['a', 'b', 'c', 'd']

, , . . :[ 'a', 'b', 'c', 'd', 'e']

:[ 'a'0, 'b'1, 'c'2, 'd'3, 'e'4 ]

Ruby . , , ? , ![ 'a' , 'b' , 'c' , 'd' , 'e' ]

. . ? , : , .maccuB = [ 'a', 'b', 'c', 'd', 'e'] maccuB[ maccuB.size - 2 ] #-> 'd'

.size, . , maccuB.size , . :maccuB = [ 'a', 'b', 'c', 'd', 'e'] maccuB[ -2 ] #-> 'd'

-2 .

. . , . :maccuB = [ 'a', 'b', 'c', 'd', 'e'] maccuB[ 1..-2 ] #-> ['b', 'c', 'd']

:

maccuB = [ 'a', 'b', 'c', 'd', 'e'] maccuB[ 1...-1 ] #-> ['b', 'c', 'd']

, .

Ruby , . :[[1],[2,3],[4]] # [[1,2],[3,4]] # [["",""],[""," "]] [["",""],[1,[""," "]]] # -

. . . : , .

, . , . ; . Ruby : . .size:

[1,'',3,'',5,6,'',2,5].size

#-> 9

, :maccuB = [1,'',3,'',5,6,'',2,5] maccuB.size #-> 9

, . , ,

.size . , . / , ? ? Ruby .max, .max_by ( 1.9). :['','','',''].max ['','','',''].max_by{ |elem| elem.size } #-> '' #-> ''

.min .min_by :['','','',''].min ['','','',''].min_by{ |elem| elem.size } #-> '' #-> 'y'

? . . , .sort .sort_by ( 1.8).['','','',''].sort #-> ['','','','']

['','','',''].sort_by{ |elem| elem.size } #-> ['','','','']

, . , . ! , . .reverse, . , , . .reverse. , :['','','',''].sort.reverse ['','','',''] ['','','',''].sort_by{ |elem| elem.size }.reverse ['','','',''] #-> #->

.reverse . ; , , . / , +:[1,2,3,4] + [5,6,7] + [8,9] #-> [1,2,3,4,5,6,7,8,9]

, , . . -, , :[ 1, 1, 2, 2, 3, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #-> [3, 3, 3, 5]

, , . , . ( ) , .

: | () & (). :[1,2,3,4,5,5,6] | [0,1,2,3,4,5,7] #-> [1,2,3,4,5,6,0,7]

. :[1,2,3,4,5,5,6,0,1,2,3,4,5,7]

, , , , . . :[1,2,3,4,5,5,6,0,1,2,3,4,5,7]

(). :[1,2,3,4,5,5,6] & [0,2,1,3,5,4,7] #-> [1,2,3,4,5]

, , . .[1,2,3,4,5,5,6] & [0,2,1,3,5,4,7]

. , | & , . . , ; , , =. , . ( ) Ruby .uniq:[1,2,3,4,5,5,6,0,1,2,3,4,5,7].uniq #-> [1,2,3,4,5,6,0,7]

, .

[1,2,3,4,5,5,6,0,1,2,3,4,5,7]

( nepBblu_maccuB + BTopou_maccuB ).uniq. , , . .flatten , . . , , , .max:maccuB = [[1,2],[3,4]] maccuB.flatten.max #-> 4

. .[[1,2],[3,4]]

, . , .[1,2,3,4]

! . (, .). : . . ... , , :maccuB_2D = [[1,2],[3,4]] maccuB_2D.map{ |maccuB| maccuB.max } #-> [2,4]

, ( ):maccuB_2D = [[1,2],[3,4]] maccuB_2D.transpose.map{ |maccuB| maccuB.max } #-> [3,4]

.transpose .

, . , , . , .["", "", "", ""] * 2 #-> ["", "", "", "", "", "", "", ""]

:maccuB = ["", "", "", ""] maccuB + maccuB #-> ["", "", "", "", "", "", "", ""]

, ? ! :maccuB = [1,2,3,4,5] maccuB[ maccuB.size ] = 6 maccuB #-> [1,2,3,4,5,6]

, - . :maccuB = [1,2,3,4,5,6] maccuB[0...-1] #-> [1,2,3,4,5]

, . .push ( ) .pop ( ):maccuB = [1,2,3,4,5] maccuB.push( 6 ) maccuB #-> [1,2,3,4,5,6] maccuB.pop #-> 6 maccuB #-> [1,2,3,4,5]

/ , . , . , [], []= +:maccuB = [1,2,3,4,5] # maccuB = [6] + maccuB maccuB #-> [6,1,2,3,4,5] maccuB[0] #-> 6 # maccuB = maccuB[1..-1] maccuB #-> [1,2,3,4,5]

, :maccuB = [1,2,3,4,5] # maccuB.unshift( 6 ) #-> [6,1,2,3,4,5] # maccuB.shift #-> 6 maccuB #-> [1,2,3,4,5]

.shift (), , , .unshift ( , ). // .shift, .unshift, .pop .push:.unshift( 0 ) .push( 6 ) [1,2,3,4,5] .shift .pop

() , () . . .shift , .pop . .push , .unshift . ,

, , , . , . , , .each ? , , . , , , .. .each mixin Enumerable. , .inject, .each_with_index ..

, (true false). , ? ( ). , : , ?. :maccuB = [1,2,2,3] puts maccuB.methods.grep(/\?$/)

, :maccuB = [1,2,2,3] puts maccuB.methods.grep(/\?$/).sort

? , ? .size .find_all:maccuB = [1,2,3,4,5,6,7] uckomoe = 5 # , maccuB.find_all{ |elem| elem == uckomoe }.size != 0 #-> true # ,

(!=, .find_all .size) ! . .include?. , :

maccuB = [1,2,3,4,5,6,7] uckomoe = 5 # , maccuB.include?( uckomoe ) #-> true # ?

, , . , .include?o3epo = [" ", "", "", "", "", "", "", "", " "] o3epo.include?("") #-> false

, . ? ?, , . , : ?nycTou_maccuB = [] noJIHbIu_maccuB = [1,2,2,3] nycTou_maccuB == [] #-> true noJIHbIu_maccuB == [] #-> false

: ?nycTou_maccuB = [] noJIHbIu_maccuB = [1,2,2,3] nycTou_maccuB.size == 0 #-> true noJIHbIu_maccuB.size == 0 #-> false

: . : .empty? (?):nycTou_maccuB = [] noJIHbIu_maccuB = [1,2,2,3] nycTou_maccuB.empty? noJIHbIu_maccuB.empty? #-> true #-> false

, , , . , -. . , , , :

: ; ; , .

. -. :maccuB = ['','','','',''] maccuB.map{ 0 } #-> [0,0,0,0,0]

.map, , , - . .map maccuB . , , .map . .map . :maccuB = [1,2,3,4,5] maccuB.map{ |elem| elem**2 }

#-> [1,4,9,16,25]

, , . .map , , |. , . elem, : _3JleMeHt x y a_He_x0tuTe_li_4awe4Ku_4a9_c_LuMoHom

BoT_Takoro 3Takoro. , . , , , ;

, . , - . , . , : , , . , , . , , , . . . , . :maccuB = [1,2,3,4,5] maccuB.map{ |elem| elem = elem**2 } # : elem ,

.map , . , .maccuB = [1,2,3,4,5] maccuB.map{ |elem| elem**2 } #-> [1,4,9,16,25] maccuB #-> [1,2,3,4,5] - .

maccuB_c_kBagpaTaMu. maccuB:maccuB = [1,2,3,4,5] maccuB = maccuB.map{ |elem| elem**2 } maccuB #-> [1,4,9,16,25]

#-> [1,4,9,16,25]

: ( ) (), . , . : .map , , . .find_all :

maccuB = [1,2,3,4,5] maccuB.find_all{ |elem| elem%2==0 }

#-> [2,4]

" elem?". , , true false. "" (==0) (%) 2.elem%2==0

, .zero?. :(elem%2).zero? (elem&1).zero? (elem[0]).zero? #

, , true, |elem| ( ), , .find_all. .find_all , true false.

, .find_all !

: ( :) ). , factorial(100) :). - .chetnoe?.()

// / . ( 1.8) .inject. , :maccuB = [1,2,3,4,5] maccuB.inject( 0 ){ |result, elem|

result + elem } #-> 15

. . result = 0 , result ( ).

. (result) . (elem) ( ), . . : result + elem.

( ) .inject ( ). ! .

, , :maccuB = [1,2,3,4,5] maccuB.inject( 0 ){ |result, elem| result = result + elem } #-> 15

result elem . . :maccuB = [1,2,3,4,5] maccuB.inject( 0 ){ |pe3yJibTaT, nepemeHHa9| pe3yJibTaT + nepemeHHa9 } #-> 15

, , . ! . :maccuB = [1,2,3,4,5] maccuB.inject( 1 ){ |pe3yJibTaT, nepemeHHa9| pe3yJibTaT * nepemeHHa9 } #-> 120

, : . : .find_all. ? .inject , .

.partition (, , ). :a = [1,2,3,4,5,6,7,8,9] a.partition{ |x| (x%3).zero? } #-> [ [3,6,9], [1,2,4,5,7,8] ]

, -. - , , , . , . ? , .find_all? ? ! , , .partition, :a = [1,2,3,4,5,6,7,8,9] one, two = a.partition{ |x| (x%3).zero? } one #-> [3,6,9] two #-> [1,2,4,5,7,8]

(multiple assignment) , . . , .

1.8 : .all? .any?. , . (, ), true false. , . , -: nil - . (false -> nil, true -> //_). - .detect. ? , . Ruby .all?. , , 1.8, :

maccuB = [1,2,2,3] maccuB.inject( true ){ |result, elem| result && ( elem > 2 ) } #-> false

. result true. result false. , maccuB . :maccuB = [1,2,2,3] maccuB.all?{ |elem| elem > 2 } #-> false

, , : , , . ? ( .all?), . Ruby .any?. , . , maccuB :maccuB = [1,2,2,3] maccuB.inject( false ){ |result, elem| result || ( elem > 2 ) } #-> true

. result false. , result true. , , .any?:maccuB = [1,2,2,3] maccuB.any?{ |elem| elem > 2 } #-> true

, , ( Ruby) .

, 8 .cumBoJIbI = ['a'..'z','A'..'Z','0'..'9'].map{ |range| range.to_a }.flatten puts (0...8).map{ cumBoJIbI[ rand( cumBoJIbI.size ) ] }.join

:maccuB = [1,2,3,4,5,6,7] maccuB.sort_by{ rand }

#->

.reverse:maccuB = [2,1,3,5,6,7,4] maccuB.sort{ |x,y| y x }

#-> [7,6,5,4,3,2,1]

, 1. , . 2. . 3. , . 4. , , - .

1. , . 2. , . . 3. . 4. . 5. . 6. , . [ [1]]

1. . 2. N- . 3. , . 4. , , . 5. ( ). 6. , . [ [2]]

1. , . 2. . 3. . 4. , . 5. . 6. , .

: , , .

, . : => . , : , , . , . , Ruby , . , . , , . . .

, :xew = {5=>3,1=>6,3=>2} xew[ 5 ] #-> 3 xew[ 2 ] #-> nil , xew[ 3 ] #-> 2

, :maccuB = [nil, 6, nil, 2, nil, 3] maccuB[ 5 ] #-> 3 maccuB[ 2 ] #-> nil maccuB[ 3 ] #-> 2

: ( nil) , . , , , , , . , , , . , , . :maccuB = [1,2,1,2,3,2,1,2,4,5] maccuB.uniq.map{ |i| [i, maccuB.find_all{ |j| j == i }.size ] } #-> [[1, 3], [2, 4], [3, 1], [4, 1], [5, 1]]

. , , ( ) . "". , . , , , . , :maccuB = [1,2,1,2,3,2,1,2,4,5] maccuB.inject( Hash.new{ 0 } ){ |result, i| result[i] += 1 result } #-> {5=>1, 1=>3, 2=>4, 3=>1, 4=>1}

""

.

Hash.new{ 0 }, : " , 0". , ( +) : " nil Fixnum". , Hash.new{ 0 } {} , . result? , result[i]+=i (, ), . , result (. .inject). result, , . , , ? .

, ( .update, 1.8). . : , . , , . , . , . DNS- IP-. DNS- IP-. ? :maccuB = [['comp1.mydomen.ru','192.168.0.3'], ['comp2.mydomen.ru','192.168.0.1'],['comp3.mydomen.ru','192.168.0.2']]

, IP- DNS , DNS:dns_name = 'comp1.mydomen.ru' maccuB.find_all{ |key, value| key == dns_name }[0][-1] #-> "192.168.0.3"

:

( ), ( ) ( : key value). , :

maccuB.find_all{ |array| array[0] == dns_name }[0][-1] #-> "192.168.0.3"

, ( , "" ). , "" .

.find_all : [ ["comp1.mydomen.ru", "192.168.0.3"] ], "192.168.0.3" . [], ( c ). [0] ["comp1.mydomen.ru", "192.168.0.3"], [-1] "192.168.0.3". .

, :xew = {'comp1.mydomen.ru' => '192.168.0.3', 'comp2.mydomen.ru' => '192.168.0.1', 'comp3.mydomen.ru' => '192.168.0.2'} xew[ 'comp1.mydomen.ru' ] #-> "192.168.0.3"

, "" . : , . , " ", . "" . , , .update:maccuB = [1,2,1,2,3,2,1,2,4,5] maccuB.inject( {} ){ |result, i| result.update( { i=>1 } ){ |key,old,new| old+new } } #-> {5=>1, 1=>3, 2=>4, 3=>1, 4=>1}

.update . , .update.

? . , , , , . - , .rehash.

maccuB_1 = [ "", "" ] maccuB_2 = [ "", "" ] xew = { maccuB_1 => 100, maccuB_2 => 300 } xew[ maccuB_1 ] #-> 100 maccuB_1[0] = "" xew[ maccuB_1 ] #-> nil xew.rehash #-> {["", ""]=>100, ["", ""]=>300} xew[ maccuB_1 ] #-> 100

(xew) (maccuB_1 maccuB_2). (maccuB_1) ( "" ""). . .rehash .

? : .hash, " " . : [1,2,3].hash #-> 25

:

? ? , ?

. , , . * Hash[]:maccuB = [1, 4, 5, 3, 2, 2] Hash[ *maccuB ] #-> {5=>3, 1=>4, 2=>2}

, ( : 1, 5 2) , , ( : 4, 3 2), . [["_1","_1"],["_2","_2"],["_3","_3"], ... ], (.flatten) :

maccuB = [[1,4],[5,3],[2,2]] Hash[ *maccuB.flatten ] #->

{5=>3, 1=>4, 2=>2}

, . , : :[["_1","_2","_3", ... ], ["_1","_2","_3", ... ]]

. .transpose ( ), .maccuB = [[1,5,2],[4,3,2]] Hash[ *maccuB.transpose.flatten ]

#-> {5=>3, 1=>4, 2=>2}

, :xew = {} xew[1] = 4 xew[5] = 3 xew[2] = 2 xew #-> {5=>3, 1=>4, 2=>2}

, . : , . , ( "" ), ( [] ), (0 0.0). , - .xew = Hash.new( "" ) xew[ " " ] += " " xew[ " " ] += ", " xew #-> { " "=>" , " }

:

xew = Hash.new( 0 ) xew[ "" ] += 60 xew[ "" ] *= 21 xew #-> {""=>1260}

: , , . , npopok (--), . . , :{ "" => 400, "" => 350, "" => 200 }

.

, , . , . , , . , . , , . .keys .values.{1 => 4, 5 => 3, 2 => 2}.keys {1 => 4, 5 => 3, 2 => 2}.values #-> [1, 2, 5] #-> [4, 3, 2]

Ruby : . , .invert. , , , .xew = {" " => 4, " " => 5} xew.invert #-> {4 => " ", 5 => " "}

, .

xew = {" " => 10, " " => 10} xew.invert #-> {10 => " "}

: xew.invert.invert . , - ? , . .update. . , . , ( ). :maccuB = [1,2,1,2,3,2,1,2,4,5] maccuB.inject( {} ){ |result, i| result.update( { i=>1 } ){ |key,old,new| old+new } } #-> {5=>1, 1=>3, 2=>4, 3=>1, 4=>1}

. .result.update( { i=>1 } ){ |key,old,new| old+new }

( .update) . { i => 1 } , . i ( .inject), . ? .

{ i=>1 }. "" i=>1

. . , . !result.update( { i=>1 } ){ |key,old,new| old+new }

. . - . . , : key, old new. . , ( ) , . . ?

result.update( { i=>1 } ){ |key,old,new| old+new }

old new. ? , key, old new. key , old (old ""), new (new ""). old+new : , . , , , i result, . ... .

, , ? , , . , ? :xew = {5=>1, 1=>3, 2=>4, 3=>1, 4=>1} xew.size #-> 5

, , => . .size , , ! . .xew = {5=>1, 1=>3, 2=>4, 3=>1, 4=>1} xew.delete( 5 ) #-> 1 xew #-> {1=>3, 2=>4, 3=>1, 4=>1} xew.delete( 5 ) #-> nil

, , , .delete. , .

.delete , , .delete nil , nil

, , .shift. , , . , ? ?

- .pop, , .shift . :xew = {5=>3,1=>6,3=>2} xew.shift #-> [5,3] xew #-> {1=>6, 3=>2}

, .shift [ , ]. , .shift . , : ? . ! , . , . , . , ( ), . , , .

, to_a. , .xew = {" " => 10, " " => 22} xew.to_a #-> [ [" ", 10], [ ", 22 ] ]

. :{[" " => 10], [" " => 22]}

{[" ", 10], [" ", 22]}

, .[[" ", 10], [" ", 22]]

, . , , .xew = {" " => 4, " " => 10} xew.sort #-> [ [" ", 4], [" ", 10] ]

, , , . .sort_by :xew = {" " => 4, " " => 10} xew.sort_by{ |key,value| value } #-> [ [" ", 4], [" ", 10] ]

. / ,

xew = {" " => 10, " " => 22} xew.max #-> [" ", 22] xew.min #-> [" ", 10]

:

[, ] ,

.max_by min_by , , 1.9 . xew = {" " => 10, " " => 22} xew.max_by{ |key,value| value } #-> [" ", 22] xew.min_by{ |array| array[0] } #-> [" ", 10]

, .sort_by : .

. , , : " !" Ruby, : " true false!" :

? ? ...

Ruby :

? ? ? , ?

. ? " ?", . " -?"nycTou_xew = {} noJIHbIu_xew = { "" => 20, "" => "", "" => 34 } nycTou_xew == {} #-> true noJIHbIu_xew == {} #-> false

" ?"nycTou_xew = {} noJIHbIu_xew = { "" => 20, "" => "", "" => 34 } nycTou_xew.size.zero? noJIHbIu_xew.size.zero? #-> true #-> false

nycTou_xew = {} noJIHbIu_xew = { "" => 20, "" => "", "" => 34 } nycTou_xew.empty? noJIHbIu_xew.empty? #-> true #-> false

...

, .empty? ? " ?", , : " ?" " ?"kapmaH = { "" => 20, "" => "", "" => 34 } kapmaH.keys.include?( "" ) #-> true

kapmaH`e "" . , .kapmaH = { "" => 20, "" => "", "" => 34 } kapmaH.key?( "" ) #-> true

kapmaH = { "" => 20, "" => "", "" => 34 } kapmaH.include?( "" ) #-> true

, .

: .member? .has_key? ? , " ?" . , : " ?" " ?"kapmaH = { "" => 20, "" => "", "" => 34 } kapmaH.values.include?( "" ) #-> false - , kapmaH.values.include?( "" ) #-> true

kapmaH = { "" => 20, "" => "", "" => 34 } kapmaH.value?( "" ) #-> true

" ?" .value?, .has_value?

: .find_all .map

,

,

.inject

, . :

( .to_a) ( ) [,]

[, ] .inject

. .xew = {" " => 4, " " => 10} xew.find_all{ |array| array[1] < 5 } #-> [ [" ", 4] ] xew.map { |array| "#{array[0]} #{array[1]}" } #-> [" 4", " 10"] xew.inject(0){ |result, array| result + array[1] } #-> 14

, . array. .

, .to_a. , array . array key, valuexew = {" " => 4, " " => 10} xew.find_all{ |key, value| value < 5 } #-> [ [" ", 4] ] xew.map { |key, value| "#{key} #{value}" } #-> [" 4", " 10"] xew.inject(0){ |result, key, value| result + value } #-> '+' nil Fixnum

, . . , nil. , array, key. value " " nil.

, :xew.inject(0){ |result, (key, value)| result + value } #-> 14

.map, , .to_a: .

xew["key"] , xew.key.class Hash def method_missing( id ) self[ id.id2name ] end end xew = {"hello" => "","bye" => ""} xew.hello #-> "" xew.bye #-> ""

, , (, ). , , .

1. . .

, . ( , ). , ( ). , . , ( ). 4- .

Ruby. : " , ". , : ucxogHoe.to_s.reverse. . , . Ruby Perl ( ). (rules).

, , , ( ) . , , Ruby, - , . , . (+, *, [] ..). , . :

C , .. . , ( ). C ( .join .split). , .

, ,

. " () ' ( // ). . , , , . . . , . , .

, ( ). ( #{ ' ' } ). ' ', . : , , . . \ ( ). : \n ( ), \t (), \\ ( ) \" ( ). , , . : "\n".size #-> 1 ? , . , . , . , , :moe_4ucJIo = 18 mou_maccuB = [1,2,3,4] puts ' = ' + moe_4ucJIo.to_s + ', ' + mou_maccuB.size.to_s

, ( ) .to_s. . :moe_4ucJIo = 18 mou_maccuB = [1,2,3,4] puts " = #{moe_4ucJIo}, #{mou_maccuB.size}"

, . .

, . , .moe_4ucJIo = 18 mou_maccuB = [1,2,3,4] puts " -- . = #{mou_maccuB.join(\",\")}"

, .. . :

moe_4ucJIo = 18 mou_maccuB = [1,2,3,4] puts " -- . = #{mou_maccuB.join(",")}"

!

:

, . . :maccuB = [4, 4, 2, 5, 2, 7] puts maccuB.max #-> 7

, . :maccuB = [4, 4, 2, 5, 2, 7] puts " maccuB'a = #{maccuB.max}" #-> maccuB'a = 7

, , ?

. , , . : . , , . , ( ) . , :ucxogHoe_4ucJIo = 123 puts " -> %b" % ucxogHoe_4ucJIo #-> -> 1111011

% ( sprintf ), . .ucxogHoe_4ucJIo = 123 puts " -> #{ ucxogHoe_4ucJIo.to_s(2) }" #-> -> 1111011

, ( ).

sprintf printf Ruby , . % puts , , , . , , . , ():cynpyr = "" cynpyra = "" cynpyr + " " + cynpyra + " = !" #-> " = !"

! . . , . ,

.ocTaJIocb_JIeT = 100 "Ky-ky! " * ocTaJIocb_JIeT #-> "Ky-ky! Ky-ky! Ky-ky! Ky-ky! Ky-ky! Ky-ky! Ky-ky!

Ky-ky! Ky-ky! "

! . , . , , . , :pe4b_kykywku = "Ky-ky! Ky-ky! Ky-ky! Ky-ky! Ky-ky! Ky-ky! Ky-ky! ... Ky-ky! Ky-ky! " ( pe4b_kykywku / " " ).size #-> 100

.size , , .size , " "

.split, . , :class String alias / :split end

, .split .

, * , .join ( , ). , .join .split , , .split , , . , , , . , , .

"Ky-ky".split('-') "Ky-ky".split('y')

#-> ["Ky","ky"] #-> ["K","-k"]

, .split. , . '-'. . .join :["Ky","ky"].join('-') ["Ky","ky"].join(',') ["Ky","ky"].join ["Ky","ky"].to_s #-> #-> #-> #-> "Ky-ky" "Ky,ky" "Kyky" "Kyky"

.join , .to_s

, .join. , :["Ky","ky"] * '-' ["Ky","ky"] * 3 #-> "Ky-ky" #-> ["Ky","ky","Ky","ky","Ky","ky"]

, ( ), , , .size:" , !".size #-> 33 "".size #-> 3

, , ! , Ruby , , . , , . , , , .

cTpoka = " , !" cTpoka[27..-1] #-> "!" cTpoka[27...-1] #-> "" cTpoka[9...14] #-> "" cTpoka[9..13] #-> ""

, -1, -2 , . ! , 1.cTpoka = " , !" cTpoka[3..3] #-> "" cTpoka[3] #-> 228

. , , [] , .cTpoka = " , !" cTpoka[3] #-> 228 cTpoka[3].chr #-> ""

, .chr - . . , (, ). .reverse. :" ! !".reverse #-> "! ! "

, . , . .reverse .reverse . , !

, "" "" " ", .sub .gsub:" ".sub("","") #-> " "

, , . , . , 18, - , 26. ( ):" 18 ".sub("18","26") #-> " 26 "

, .sub? .gsub .sub. , ", "cTpoka = "- " cTpoka.sub("","") #-> "- " cTpoka.gsub("","") #-> "- " cTpoka.gsub("","").gsub("","") #-> "- "

.sub , .gsub .sub .gsub

.sub substring () .gsub Perl. , , s///g, /g ( global , )

, . .scancTpoka = "- " cTpoka.scan("") #-> ["",""] cTpoka.scan("").size #-> 2 cTpoka.scan("").size #-> 2 cTpoka.scan("").size + cTpoka.scan("").size

#-> 4

.scan . , .size , .scan

, . ! .scan, . ! ?! . , , , . . Ruby / ( ). :/(|)/ /\w+@[\w\.]+\w+/i

? . . . :

. , . . . , . . ,

. , " " . , " "

. , .

, . :/[]/ /[--]/ /[0-9a-z]/ /[^0-9]/ #-> #-> #-> #-> ,

- () ( ) ^ (), ,

\s \S \d \D \w \W .

[\f\t\n\r ] [^\f\t\n\r ] [0-9] [^0-9] [a-zA-Z0-9] [^a-zA-Z0-9] [^\n\r]

, , , ,

! , ? ...

(, ). ( ). :/\w{3}/ /\d{1,3}/ /[--]{3,} #-> #-> , #->

( )

* + ? {0,} {1,} {0,1}

. ? ,

, . , . ( ). , , | (, ). :/(|)/ /(\w+|[--]+)/ #-> "", "" #-> ,

.any? .all? .inject. . ,

, . , HTML-

URL. , . , . $1, $2, ..., $9. " ". :"2+7*3".gsub(/(\d+)\*(\d+)/){ $1.to_i * $2.to_i } #-> "2+21"

!

. , (?:) (?!) .

, . , ./^\d+/ /\w+$/ /^$/ #-> #-> #->

, ^ $

.

. ( ). :/(hello|world)/i /\s+/mix #-> "hello", "world". #->

:

multiline ignorcase

extended

, mix

, .split . , . .", , !".split(/[,\.?! ]+/) #-> ["","",""]

, . . , .sub .gsub , . , :"- ".gsub(/(|)/){ $1 + '' } #-> "- "

, ! , "" . :"- ".gsub(/(|||)/){ $1 + '' } #-> "- "

, . ? . :/(|||)/

:

(|||)

. . ? , :{ $1 + '' }

, $1 ( ) . , $1 , .

, , $1 ( ), $2 ( ) $9 ( ) $1-$9 Perl

? !"- ".gsub(/([])/){ $1 + '' } #-> "- "

, . , . :

, ? ?

! ( ) :", , !".gsub(/[-]+/){ |cJIoBo| cJIoBo.reverse } #-> ", , !"

cJIoBo, geJIom.

.scan . ? :", , !".scan(/[--]+/) #-> ["","",""]

? :", , !".scan(/[,\.;:! ]+/) #-> [", ",", ","!"]

.scan , , .. (?:). .scan , , , .cTpoka = "495-506-13 56 [email protected](34) 1.5.1232 12.14.56 31..9999" cTpoka.scan(/(?:[-a-z_\.])*@(?:[-a-z])*(?:\.[a-z]{2,4})+/) #-> ["[email protected]"]

, , (?:) () . .scan . , [] .", , !"[/[--]+/] #-> ""

[] , , nil [] , " , ?" ( ) .

, .scan .split, , .TekcT.scan( npaBuJIo ) + TekcT.split( npaBuJIo ) = TekcT

, .split ,

, . .scan, [] =~ ( Perl), [] . {n,m} .

m ( ) , n. () . . , HTML ( ). . . , : . . , m n, , n m. ? () .", , !".scan(/[--]+?/) #-> ["","","","","","","","",""] " , !".gsub(/([]??)/){ $1 + '' } #-> " , !"

. .

( http://ruby-forum.ru) : (wrap). , , : , , , n ( n=80). , , . ... , , . wrap.

class String def wrap(col = 80) gsub(/(.{1,#{col}})( +|$\n?)|(.{1,#{col}})/,"\\1\\3\n") end end

... .wrap String. , ( ) "" ( " "). :p "wrapping text with regular expressions".wrap( 10 ) # -> "wrapping\ntext with\nregular\nexpression\ns\n"

. , 80. .(.{1,80})( +|$\n?)|(.{1,80})

, :

(.{1,80}) 1 80 (). $1 ( ) "\\1" ( +|$\n?) . $2 ( ) "\\2". $\n?, " ($), (\n)". , $2 (?: ) ( ) | (.{1,80}) 1 80 (). $3 ( ) "\\3"

1 2 3. , , 80. , 80 . , , , , . . , ( ). ( .) . , . (

). (): http://macromates.com/blog/archives/2006/06/28/wrapping-textwith-regular-expressions/ . , .to_s:class Container def to_s "" end end cont = Container.new p " #{cont}" #-> " "

, , Comparable to_str. Ruby, String , .class Container include Comparable def to_str "" end def to_s "" end def (other) to_s other.to_s end end cont = Container.new "" == cont #-> true

1. , . . 2. , , . , . 3. . 4. ( ). , "".

. . "".

5. "::". 6. (, "" "Ruby", "" "Java").

. .

7. , .

, .

8. "..".

, 31, 12. . "31..2001".

9. . URL (, http://ru.wikibooks.org/wiki/Ruby http://ru.wikibooks.org ).

Ruby , . , . . def end.

, - , Ruby , -"" . def ... enddef sum(a, b) return a + b end sum(10, 2) #-> 12

Ruby , return . , " " :

def sum(a, b) a + b end sum(10, 2) #=> 12

; , " "def sum(a, b = 5) a + b end sum(10, 2) #-> 12 sum(10) #-> 15

Ruby . - . , true false. -, . , Java is: isVolatile(),isEnabled

, , , :arr = [] if arr.length == 0 puts "empty" else puts "not empty" end

Ruby - .empty?, true , - .any?, true .arr = [] if arr.empty? puts "empty" else puts "not empty" end

, , -.

:arr = [1,2 ,3] p "Array has something" if arr.any?

, .string = " Some string with spaces " string.strip! #-> "Some string with spaces" - ... string #-> "Some string with spaces" #=> ... -

- . , :class Bottle def capacity @capacity end def capacity=(new_cap) @capacity = new_cap end end bytilka = Bottle.new bytilka.capacity = 10 #-> 10, capacity=

(, , - !) - . :class BeHuK def+(another) 12 + another end end meTeJIka = BeHuK.new meTeJIka + 10 #-> 22

, , Ruby Time.

Time :t = Time.now #-> Sun Jun 11 20:29:51 t + 60 #-> Sun Jun 11 20:30:51 -

Date, , Time, require 'date' d = Date.today #-> Sun Jun 11 d + 1 #-> Mon Jun 12 -

"" "" - def sum(*members) members[0] + members[1] end sum(10, 2) #-> 12

, def sum(*members) initial = 0 members.collect{ | item | initial += item } initial end sum(10, 2) #-> 12 sum(10, 2, 12, 34) #-> 58

, "". , " " . , . :array_to_sum = [10, 2, 12, 34] sum(*array_to_sum) #-> 58

: ,

. . Ruby - ****. Ruby - , ( each map). " " - , , , . , - ...

,

do... end . , . , .map. . .puts (1..3).map(){ "Bay!" } # Bay!

, :puts (1..3).map{ "Bay!" } # Bay!

, , , , !puts (1..3).map{ word = 'Bay!'; word } #-> Bay! # word puts word # -

, do ... end

puts (1..3).map do random_number = rand() "Bay - !\n"+ random_number.to_s end

, , . , , "", . , .map , :puts (1..3).map do | index | index end

index , 1! do , . L, "" .method { | argument | .. }

yield , [] .def pa3_u_gBa yield "u pa3" yield "u gBa" end pa3_u_gBa { | cJloBa | puts "!!! " + cJloBa } #-> !!! u pa3 #-> !!! u gBa

cJloBa . , :

def twice(&block) yield "u pa3" yield "u gBa" end twice #-> LocalJumpError -

. . . , , , :def func(a,&block) return a if a yield "u pa3" yield "u gBa" end func true #-> true func false #-> LocalJumpError: no block given

, pa3_u_gBa . , :def func(a,&block) return a if a block ||= lambda{ | cJloBa | puts "!!! " + cJloBa } block.call("u pa3") block.call("u gBa") end func true #-> true func false #-> !!! u pa3 #-> !!! u gBa func(false) { | cJloBa | puts "??? " + cJloBa } #-> ??? u pa3 #-> ??? u gBa

lambda - , block.call - . , :def writing_to(file, &block) File.open(file, 'w', &block) end

Ruby.

, . " ": . , -. , , . , , .connected { download_email }

download_email, ( ) connected:def connected connect_to_internet result = yield disconnect result end

, , . , , "", "_", " ", "". , :def connected connect_to_internet begin result = yield ensure disconnect end result end

, .

, , . , : . , " " , . , .

. .size , .size . , . , .find_all{ ... }. size. :maccuB = [1,2,3,4,5,6] maccuB.size{ |i| (i%2).zero? }

#-> 3

, .size , :class Array def size( &block ) block ? inject( 0 ){ |count,elem| (yield elem ) ? count + 1 : count } : length end end

, . , 3 6 :3 + rand( 4 )

? ? :(3..6).rand

, ? Range:class Range def rand first + Kernel.rand( last - first end end

+ ( exclude_end? ? 0 : 1 ) )

:

p Array.new(100){ (3..6).rand }.uniq.sort

#-> [3,4,5,6]

! , : , Range#rand . . Array#rand ( ), Range#rand .to_a.rand. , Ruby:class Array def rand self[ Kernel.rand( size ) ] end end class Range def rand to_a.rand end end

:p Array.new(100){ ('a'..'c').rand }.uniq.sort #-> ["a","b","c"]

, !

//? , Ruby , . , , ( ). , :class BeHuK def mecTu end end BeHuK.instance_methods #-> [..., "mecTu", ...] class BeHuK def noMblTb_B_yHuta3e(yHuTa3) end end BeHuK.instance_methods #-> [..., "mecTu", ..., "noMblTb_B_yHuta3e", ...]

.instance_methods , , .

, . , Ruby "", "", , . , self. String, :str = "Crazy fox jumps over a lazy dog" class String def consonants cons = [] self.scan /[BCDFGHJKLMNPRSTbcdfghjklmnprst]/ do | m | cons "Crfjmpsldg"

( ) . Ruby consonants . , self :str = "Crazy fox jumps over a lazy dog" class String def self.consonants_from(str) cons = [] str.scan /[BCDFGHJKLMNPRSTVWZbcdfghjklmnprstvwz]/ do | m | cons "Crfjmpsvlzdg"

Ruby , Class, . Ruby . , . self - . . , File open. File, , . ,

/tmp:class File def self.temporary(&block) # # dirname expand_path - File.dirname File.expand_path my_dir = self.dirname(self.expand_path(__FILE__)) base = basename(__FILE__, '.rb') # -> .rb stamp = "#{base}_#{Time.now.to_i}.tmp" # -> tmp # File.join Windows UNIX path = join(my_dir, stamp) self.open(path, 'w', &block) end end File.temporary { |f| f 'localhost', 'Port' => 31337, "Prompt" => /^\+OK/n ) client.cmd("ls"){ |str| puts str } client.cmd("cd .."){ |str| puts str } client.cmd("ls"){ |str| puts str } client.close

, !

, , Geka , :system( "telnet " + gets ) loop{ system( gets ){ |str| puts str } }

, . system, ( telnet). telnet, . . , , ( ls, cd shutdown).

? online-. , ERB. , ERB , . , . PHP -, . - ( Ruby), . : "", notepad.txt. http://localhost:8080.

8080, - 80 Skype. , , , :require 'webrick' server = WEBrick::HTTPServer.new( :Port => 8080 )

server.mount_proc('/'){ |req,resp| File.open('notepad.txt','w'){ |f| f.write( req.query["text"] ) } if req.query["text"] resp['Content-Type'] = 'text/html' resp.body = %& #{IO.read('notepad.txt')}
& } server.start

. , : require 'webrick'

WEBrick ( ). :Port => 8080

, 80 . . 8080 . , , . server.mount_proc('/')

. http://localhost:8080/, . , , '/' , '/notepad'. , http://localhost:8080/notepad. , ? { |req,resp| ... }

( ) . req ( , ), resp ( , ). ... if req.query["text"]

if. , if , text. .query {_ => }. File.open('notepad.txt','w'){ |f| f.write( req.query["text"] ) }

notepad.txt text ( ). resp['Content-Type'] = 'text/html'

. , , , . Content-Type.

resp.body = %& ... &

.body= HTML- . HTML- , %& ... & . . % , ( & ). , ( ). server.start

.start -.

, -, . Ctrl+Break Ctrl+C , . , . ERB ERB. , Ruby-. :

. .

. . ERB ( .result) , ERB "PHP, Ruby". , . ERB "PHP Ruby".

WEBrick PHP- CGI- , ERB:require 'webrick' require 'erb' server = WEBrick::HTTPServer.new( :Port => 8080 ) server.mount_proc('/'){ |req,resp| File.open('notepad.txt','w'){ |f| f.write req.query["text"] } if req.query["text"] resp['Content-Type'] = 'text/html'

wa6JIoH = %&
& resp.body = ERB.new( wa6JIoH ).result } server.start

? , : require 'erb'

ERB. wa6JIoH = %& ... ... &

wa6JIoH , ERB-. notepad.txt. ERB. resp.body = ERB.new( wa6JIoH ).result

ERB ERB-. .result .body=, . ? "" "" ? . ERB . Ruby- HTML. " - !" () ERB- ERB- Ruby-. , . , ERB- . , . ERB- (index.html) :

, c ERB-

(index.html).require 'webrick' require 'erb' server = WEBrick::HTTPServer.new( :Port => 8080 ) server.mount_proc('/'){ |req,resp| File.open('notepad.txt','w'){ |f| f.write req.query["text"] } if req.query["text"] resp['Content-Type'] = 'text/html' resp.body = ERB.new( IO.read('index.html') ).result } server.start

, ! , WEBrick ERB-... ! ERB- ERB- ERB- , ERB-, , , . , :require 'webrick' server = WEBrick::HTTPServer.new( :Port => 8080 ) server.mount('/',WEBrick::HTTPServlet::ERBHandler,'index.html') server.start

, require 'erb' . , ERB- ERB , , index.html ( ERB-):

, , text notepad.txt. . : text query, req.query. !

... ? notepad.rb.

-. . , . , .index.html.

ERB-. , -.notepad.txt.

. , .

, , . : .

,

? , Ruby. ping ( ). ping.rb. pingecho. :require 'ping' host = ARGV[0] || "localhost" printf("%s alive? - %sn", host, Ping::pingecho(host, 5))

. Timeout::Error Errno::ECONNREFUSED. Timeout. :require 'socket' require 'timeout' def ping( host, service = "echo",timeout = 5) begin timeout( timeout ){ TCPSocket.open( host, service){} } rescue Errno::ECONNREFUSED true rescue false else true end end p ping(ARGV[0] || "localhost")

, , .

TCPSocket . ( ) - ( -), false. , true. , .

- ... , . SMTP . , . ( ), , ( ). , . :

; ; .

... . Cron, . , SMTP :require 'socket' request = "" begin_time = Time.now t = TCPSocket.open('mail.scli.ru', 'smtp'){ request = t.gets.chomp t.close end_time = Time.now File.open( Time.now.strftime('d:/logs/smtp/%Y_%m_%d.smtp'), File::APPEND | File::CREAT | File::WRONLY ){ |f| f.puts( "#{sprintf( '%02d',Time.now.hour )} | #{end_time-begin_time} | #{request}" ) }

, . . :request = t.gets.chomp

, . , TCP/IP. . .345 SMTP . , , NOOP. .

require 'socket' request = "" begin_time = Time.now t = TCPSocket.open('mail.scli.ru', 'smtp') t.puts('NOOP') request = t.gets.chomp t.close end_time = Time.now File.open( Time.now.strftime('d:/logs/smtp/%Y_%m_%d.smtp'), File::APPEND | File::CREAT | File::WRONLY ){ |f| f.puts( "#{sprintf( '%02d',Time.now.hour )} | #{end_time-begin_time} | #{request}" ) }

! ... . : ( ). , timeout. " " timeout. . , :require 'timeout' require 'socket' request = "" beachmark = "" begin beachmark = Time.now timeout(1){ t = TCPSocket.open('mail.scli.ru', 'smtp') t.puts('NOOP') request = t.gets.chomp t.close } beachmark = Time.now - beachmark rescue beachmark = 'timeout' end File.open( Time.now.strftime('d:/logs/smtp/%Y_%m_%d.smtp'), File::APPEND | File::CREAT | File::WRONLY ){ |f| f.puts( "#{sprintf( '%02d',Time.now.hour )} | #{beachmark} | #{request}" ) }

, beachmark "-", beachmark. :require 'timeout' require 'socket' require 'benchmark' request = "" beachmark = "" begin beachmark = Benchmark.measure{ timeout(1){

t = TCPSocket.open('mail.scli.ru', 'smtp') t.puts('NOOP') request = t.gets.chomp t.close } }.to_s rescue beachmark = 'timeout' end File.open( PATH_LOG_SMTP + Time.now.strftime('d:/logs/smtp/%Y_%m_%d.smtp'), File::APPEND | File::CREAT | File::WRONLY ){ |f| f.puts( "#{sprintf( '%02d',Time.now.hour )} | #{beachmark} | #{request}" ) }

, Beachmark . :user system total ( real )

real. . measure:beachmark = Benchmark.measure{ timeout(1){ t = TCPSocket.open('mail.scli.ru', 'smtp') t.puts('NOOP') request = t.gets.chomp t.close } }.real

Benchmark.measure Benchmark.realtime. . ;rescue. . . , , :require 'socket' require 'benchmark' require 'timeout' request = "" beachmark = "" begin timeout(1){ beachmark = Benchmark.measure{ request = TCPSocket.open('mail.scli.ru', 'smtp'){ |t| t.puts('NOOP') t.gets.chomp }[0..2] }.real } rescue Timeout::Error

beachmark = 'timeout' rescue beachmark = ' ' request = 'error' end File.open( Time.now.strftime('d:/logs/smtp/%Y_%m_%d.smtp'), File::APPEND | File::CREAT | File::WRONLY ){ |f| f.puts( "#{sprintf( '%02d',Time.now.hour )} | #{beachmark} | #{request}" ) }

: , SMTP, HTTP, FTP, POP3 .? .

, . , , . ! . :

. . . http://www.minjust.ru. , , . 1-2 . , ( ). . .

, ? . (, , , ...) . , . . ( , ) . , ... . . . , ' ^_^ '. - ( )... !

, . . , n-. . , . . ! . , :require 'net/http' h = Net::HTTP.new( 'www.minjust.ru', 80 ) resp, data = h.get( '/index.html' ) dates = data.scan(/(d{4}-d{2}-d{2})/).map{ |ar| ar[0] } texts = data.scan(/(.*?)/m ).map{ |ar| ar[0].gsub("n",' ').gsub("r"," ").gsub(' '*2, ' ').strip } File.open( Time.now.strftime('log/%Y_%m.log'), File::APPEND | File::CREAT | File::RDWR ){ |f| from_inet = (0...5).inject([]){ |result, i| result + [ dates[i] + ' ^_^ ' + texts[i] ] } from_file = f.readlines.map{ |str| str.chomp }.compact f.puts( ( from_inet - (from_file & from_inet) ).sort ) }

, . .

- HTML- HTML- HTTP. URL. HTTP. Net::HTTP ( Socket', ). RubyBook.html.require 'net/http' Net::HTTP.open('ru.wikibooks.org'){ |http| File.open('RubyBook.html','w'){ |file| file.write http.get('/wiki/Ruby').body } }

Net::HTTP , URL : (ru.wikibooks.org) (/wiki/Ruby). , HTML- . . . open open-uri. URL ( HTTP).

require 'open-uri' File.open('RubyBook.html','w'){ |file| file.write open( 'http://ru.wikibooks.org/wiki/Ruby' ).read }

, URL ( http://) ( . boby), ( . head). . ( ), , , HTTP- . , HTTP- . , . , Net::HTTP:require 'net/http' Net::HTTP.open('ru.wikibooks.org'){ |http| p http.head('/wiki/Ruby') }

, . , , .get .head. ? :require 'net/http' Net::HTTP.open('ru.wikibooks.org'){ |http| head, body = http.get('/wiki/Ruby') }

.get . , . , open open-uri:require 'open-uri' p open( 'http://ru.wikibooks.org/wiki/Ruby' ).meta

.read .meta . ( Hash), ( MIME), .

:require 'open-uri' open( 'http://ru.wikibooks.org/wiki/Ruby/' ){ |f| p f.meta p f.read }

.open . - , . IP- . HTTP- , (, , ). , http- . Net::HTTP::Proxy:require 'net/http' Net::HTTP::Proxy('you.proxy.host',8808).start('ru.wikibooks.org'){ |http| p http.get('/wiki/Ruby').body }

. - you.proxy.host, - 8808. , open ( open-uri).require 'open-uri' p open( 'http://ru.wikibooks.org/wiki/Ruby',:proxy => 'http://you.proxy.host:8808/').read

( ) open. , (, ).

open , , .

Net::HTTP Net::HTTP::Proxy ( ).

You have got mail - , - HTTP . , . WEBrick (http://www.webrick.org), . , . , .

WEBrick ( ) -. Mongrel ( , . , . ), , , . - WEBrick , . , . , , . , : web . , . , WEBrick :require 'webrick' WEBrick::HTTPServer.new( :DocumentRoot => 'public_html', :Port => 8080 ). start

, Firefox : http://localhost:8080/. , public_html . public_html/index.html : !

: " !" ! -. , Ctrl+Break . - , : require 'webrick'

WEBrick. . WEBrick::HTTPServer.new( :DocumentRoot => 'public_html', :Port => 8080 ).start

WEBrick , : WEBrick::.HTTPServer

, -

.

.new WEBrick::HTTPServer. ( )::DocumentRoot => 'public_html' , - ./public_html html- (

) . , .

8080 . , 80 ( -). , 80- , Skype. . , 80 . , .:Port => 8080

.start . GServer, .sleep loop .

. WEBrick. -, . , ! . : html- (index.html) (/input). public_html/index.html . . /input , .

public_html/index.html:

-1 - 01 02 - - 04 05 - - 06 09 - - 10 11 - -1 - 12 14 - -3 - 17 18 - -2 - 19 20 - - 21 22 - - 25 27 - - 30 34 - - 57 58 - - 61 62 - - 64 67 - - 74 76 - - 81 82 - - 85

Geka, , : " ?" , -, , , , , . , , FORM. , . action='/input'

, . CGI, . /input.

method='post'

HTTP : POST GET. , POST . POST. FORM INPUT, . INPUT : NAME TYPE. TYPE="checkbox"

TYPE . checkbox (). : "on" () "off" (). "off" . . NAME="check_01"

=. NAME . . index.html (Firefox): ( /input), ( public/index.html). . .bosses = { 'check_01' => "\t -1\t ..", 'check_02' => "\t \t ..", 'check_04' => "\t \t ..", 'check_05' => "\t \t ..", 'check_06' => "\t \t ..", 'check_09' => "\t \t ..", 'check_10' => "\t \t ..", 'check_11' => "\t \t ..", 'check_12' => "\t -1\t ..", 'check_14' => "\t \t ..", 'check_17' => "\t -3\t ..", 'check_18' => "\t -2\t ..", 'check_19' => "\t \"\"\t ..", 'check_20' => "\t \t ..", 'check_21' => "\t \t ..", 'check_22' => "\t \t ..", 'check_25' => "\t \t ..", 'check_27' => "\t \t ..", 'check_30' => "\t \t ..", 'check_34' => "\t \"\"\t ..", 'check_57' => "\t - \t ..", 'check_58' => "\t \t ..", 'check_61' => "\t \t ..", 'check_64' => "\t \t ..", 'check_62' => "\t \t ..", 'check_67' => "\t \t ..", 'check_74' => "\t \t ..", 'check_76' => "\t \t ..", 'check_81' => "\t \t ..", 'check_82' => "\t \t ..", 'check_85' => "\t \t ..", 'check_001' => "\t \t ..", 'check_002' => "\t \t ..", 'check_003' => "\t \t ..", 'check_004' => "\t \t ..", 'check_005' => "\t \t ..", 'check_006' => "\t \t ..",

'check_007' => "\t \t ..", 'check_008' => "\t \t ..", 'check_009' => "\t \t ..", 'check_010' => "\t \" \"\t ..", 'check_011' => "\t \"-\"\t ..", 'check_012' => "\t \t .." } require 'webrick' server = WEBrick::HTTPServer.new( :Port => 8080 ) server.mount_proc('/'){ |req,resp| resp.body = IO.read('public_html/index.html') } server.mount_proc('/input'){ |req,resp| resp.body = %! #{req.query.map{ |key,value| bosses[ key ] }. compact.join("\n") }
! } server.start

-: bosses = { ... }

, . , , . . require 'webrick'

WEBrick. - . , -. server = WEBrick::HTTPServer.new( :Port => 8080 )

WEBrick::HTTPServer. server. . :DocumentRoot , public_html/index.html . public_html . server.mount_proc('/'){ |req,resp| resp.body = IO.read('public_html/index.html') }

.mount_proc('/') , http://localhost:8080/ . req resp (req) (resp), req resp (resp.body = ). public_html/index.html. , , .

server.mount_proc('/input'){ |req,resp| ... }

/input, . :

resp.body = ... ( HTML-).

HTML-: #{..}
;

. , TEXTAREA. , . :

: req.query.map{ |key,value| bosses[ key ] }. compact.join("\n"); ( .query) bosses. .join("\n").

server.start

.

. , ( ), , - . -! , . , WEBrick

( ). , :DocumentRoot => 'public_html' .new. -. WEBrick::HTTPServlet::FileHandler.

CGI- CGI-, . , . CGI- Ruby : #!/usr/bin/ruby

Unix #!c:/ruby/bin/ruby.exe

Windows

, , Windows CGI- . , WEBrick , , (./sctipt_name) . , Windows . WEBrick, CGI-. , , , :File.open(Config::CONFIG['rubylibdir']+'/webrick/httpservlet/cgi_runner.rb', 'w'){|file| file.puts IO.read($0).split('#'*10).last } exit ########## # # cgi_runner.rb -- CGI launcher. # # Author: IPR -- Internet Programming with Ruby -- writers # Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU # Copyright (c) 2002 Internet Programming with Ruby writers. All rights # reserved. # Copyright (c) 2007 Rubynovich # # $IPR: cgi_runner.rb,v 2.0 2007/02/23 18:53:15 Rubynovich Exp $ STDIN.binmode STDOUT.reopen(open(STDIN.sysread(STDIN.sysread(8).to_i), "w")) STDERR.reopen(open(STDIN.sysread(STDIN.sysread(8).to_i), "w")) ENV.clear ENV.update( Marshal.restore(STDIN.sysread(STDIN.sysread(8).to_i)) ) if IO.read(ENV["SCRIPT_FILENAME"],50) =~ /^#!(.*)$/ exec($1,ENV["SCRIPT_FILENAME"]) else exec(ENV["SCRIPT_FILENAME"]) end

. -- , . CGI- WEBrick::HTTPServlet::CGIHandler

ERB- ERB-, .

, .mount_proc. ( .mount_proc).

, WEBrick , mount_file ( ), mount_erb ( ERB-) mount_cgi ( CGI-). mount_proc (, ). :

require 'webrick' module WEBrick class HTTPServer ['ERB','CGI','File'].each{ |handler| class_eval( "def mount_#{handler.downcase}(point,file)\nmount(point,HTTPServlet::#{handler}Han dler,file)\nend" ) } end end

:require 'webrick' module WEBrick class HTTPServer ['ERB','CGI','File'].each{ |handler| class_eval( "def mount_#{handler.downcase}(point,file)\nmount(point,HTTPServlet::#{handler}Han dler,file)\nend" ) } end end server = WEBrick::HTTPServer.new( :Port => 8090 ) server.mount_file('/','html') server.mount_cgi('/hello','cgi-bin/hello.exe' ) server.mount_cgi('/hello.cgi','cgi-bin/hello.rb' ) server.start

, .

/ / / / / / RubyNews . , . /

Ruby on rails. Ruby on Rails ( ) . . Ruby

Ruby . () . . .. Rolling with Ruby on Rails. (pdf). Ruby. . . ( ) FAQ Ruby. Ruby. Ruby, .., .. . ..

Whys (Poignant) Guide to Ruby(.) , . . . ; , .. . Programming Ruby (.). , . Windows. (, ). Amazon.com . Ruby.on-page.net(.) Ruby

- ( , ) . http://ru.wikibooks.org/wiki/Ruby : | Ruby | -

: 06:35, 27 2007. GNU Free Documentation License.