Created
March 5, 2011 18:04
-
-
Save SaitoWu/856554 to your computer and use it in GitHub Desktop.
some ruby language exercise
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 call_block | |
puts "before call" | |
yield | |
yield | |
puts "after call" | |
end | |
call_block{ puts "call" } #before call\ncall\ncall\nafter call | |
def args(*args) | |
puts *args.join("-") | |
end | |
args "12","123","1234" #=> 12-123-1234 | |
def block_args | |
if block_given? | |
puts yield 3 | |
end | |
end | |
block_args{ |x| x+3 } #=> 6 | |
def block_args0(&block) | |
puts block.call(3) | |
end | |
block_args0{ |x| x+4 } #=> 7 | |
class Array | |
def each0 | |
if block_given? | |
for x in self | |
yield x | |
end | |
end | |
end | |
def each1(&block) | |
self.each do |x| | |
if x.class == Array | |
x.each &block | |
else | |
block.call x | |
end | |
end | |
end | |
def sum0 | |
@sum = 0 | |
if block_given? | |
for x in self | |
@sum += yield x | |
end | |
end | |
@sum | |
end | |
end | |
[1,2,3].each0{|x| puts "x: #{x}"} #=> x: 1\nx: 2\nx: 3 | |
[1,2,[3,3],4].each1{ |x| puts "x: #{x}"} #=> x: 1\nx: 2\nx: 3\nx: 3\nx: 4 | |
puts [1,2,4].sum0{ |x| x%2==0 ? x : 0 } #=> 6 | |
module Mix_thing | |
def shut_up | |
puts "mix mix mix" | |
end | |
end | |
class Mix | |
include Mix_thing | |
end | |
mix = Mix.new | |
mix.shut_up #=> mix mix mix | |
class Object | |
define_method(:meta) do |*args| | |
args.each{|c| puts c} #=> com\nnet | |
end | |
end | |
class MetaO | |
meta :com, :net | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment