ruby practice

来源:互联网 发布:python 列表中的元组 编辑:程序博客网 时间:2024/05/18 10:32
 

classAmbiguous

  defx

    1

  end

  deftest

    putsx

    x= 0 if false

    putsx

    x= 2

    putsx

  end

end

am= Ambiguous.new

am.test

 

#! /usr/bin/ruby
#
#我们首先用“catch(:done)”标注了一个块,
#当执行到“throw :done”时,中止当前“catch(:done)”所标注的块,
#处理流程继续向下处理。 在catch/throw中,当碰到throw时,
#Ruby会展开调用堆栈来查找匹配的catch,
#当找到后,堆栈会被展开,catch块剩余的代码不会被执行。
#Ruby中没有goto 语句,但你可以使用catch/throw或异常来实现goto的功能。
#
def m(n)
  puts n
  throw :done unless n > 0
  m(n-1)
end
catch(:done) {
  m(3)
  puts "Cannot reach here!"
}
puts "Reach here!"

 

class FixedStack < Stack
  def initialize(limit)
    super()
    @limit = limit
  end
  def push(val)
    if @sp >= @limit
      puts "Over limit"
      return
    end
    super(val)
  end
  def top
    return @stack[-1]
  end
end

 

#! /usr/bin/ruby

require"observer"
require"tk"

classWatchModel
  includeObservable
  definitialize
    @running= false
    @time= 0
    @last= 0.0

    Thread.startdo
      loopdo
        sleep0.01
        if@running
          now= Time.now.to_f
          @time+= now - @last
          puts@time
          @last= now
          changed
          notify_observers(@time)
        end
      end
    end
  end

  defstart_stop
    @last= Time.now.to_f
    @running= ! @running
  end

  deftime
    @time
  end
end

classWatchWindow

  definitialize
    model= WatchModel.new
    model.add_observer(self)

    @label= TkLabel.new(nil).pack('fill'=>'x')
    self.update(0)
    btn= TkButton.new
    btn.text("start/stop")
    btn.command(proc{model.start_stop})
    btn.pack('fill'=> 'x')
    btn= TkButton.new
    btn.text('quit')
    btn.command(proc{exit})
    btn.pack('fill'=> 'x')
    Tk.mainloop
  end

  defupdate(time)
    @label.textformat("%02d:%02d",time.to_i,(time-time.to_i)*100)
  end

end

WatchWindow.new

 

require "observer"

classTick

  includeObservable

  deftick

    loopdo

      now= Time.now

      ifnow.sec[0]!= 1

        changed

      end

      notify_observers(now.hour,now.min,now.sec)

      sleep1.0 - Time.now.usec/ 1000000.0

    end

  end

end

classTextClock

  defmy_update(h,m, s)

    printf"\e[8D%02d:%02d:%02d",h, m,s

    STDOUT.flush

  end

end

if$0 == __FILE__

  tick= Tick.new

  tick.add_observer(TextClock.new,:my_update)

  tick.tick

end

 

#! /usr/bin/ruby

defadd_gram_to_multi_word(token)

  pron= token.split("-").collect{| w | w.chomp.strip}.join(" ")

  stories= Dir.glob('stories/*')

  stories.eachdo |story|

    story_changed= false

    File.openstory do |file|

      arr= file.collectdo |line|

              ifline =~ /<w .* t="#{token}" .*\/>/

                gram= "<gram t=\"#{pron}\" />"

                putsline

                story_changed= true

                num_of_white_space= line.index(/<w/)

                putsnum_of_white_space

                prefix_t= " " * (num_of_white_space + 4)

                prefix_w= " " * num_of_white_space

                line.gsub!(/\s*\/>/,">")

                gram= prefix_t +gram + "\n"

                sub_w= prefix_w +"</w>\n"

                putsline + gram + sub_w

                line+ gram + sub_w

              else

                line

              end

            end

      ifstory_changed

        File.open(story,"w") do |f|

          arr.eachdo |a|

            f.write(a)

          end

        end

      end

    end

  end

end

token_list= ["multi-vitamin"]

token_list.eachdo |token|

  add_gram_to_multi_wordtoken

end

 

require'singleton'

classPrintSpooler
  includeSingleton

end

 

classRange
  defby(step)
    x= self.begin
    ifexclude_end?
      whilex < self.end
        yieldx
        x+= step
      end
    else
      whilex <= self.end
        yieldx
        x+= step
      end
    end
  end
end

 

module Seq

  defself.fromtoby(from,to, by)

    x= from

    whilex <= to

      yieldx

      x+= by

    end

  end

end

if__FILE__ == $0

  Seq.fromtoby(1,10, 2){|x|puts x}

end

 

classStack
  definitialize
    @stack= []
    @sp= 0
  end

  defpush(value)
    @stack[@sp]= value
    @sp+= 1
  end

  defpop
    returnnil if @sp== 0
    @sp-= 1
    return@stack.pop
  end

  defto_s
    @stack
  end
end

 

require "builder/xmlmarkup"

xml= Builder::XmlMarkup.new(:indent=> 2)

putsxml.html {

  xml.head{

    xml.title("History")

  }

  xml.body{

    xml.h1("Header")

    xml.p{

      xml.text!("paragraph with")

      xml.a("a Link","href" => "http://onestepback.org")

    }

  }

}

 

class Sequence
  def initialize(from, to, by)
    @from, @to, @by = from, to, by
  end
  def each
    x = @from
    while x <= @to
      yield x
      x = x + @by
    end
  end
  def length
    return 0 if @to < @from
    Integer((@to - @from)/@by) + 1
  end
  def [](index)
    return nil if index < 0
    v = @from + index*@by
    if v <= @to
      v
    else
      nil
    end
  end
  def *(factor)
    Sequence.new(@from*factor, @to*factor, @by*factor)
  end
  def +(offset)
    Sequence.new(@from + offset, @by + offset, @by)
  end
end
if __FILE__ == $0
  s = Sequence.new(1, 10, 2)
  s.each {|x| puts x}
end

原创粉丝点击