hybridgroup / rubyserial

FFI Ruby library for RS-232 serial port communication
https://rubygems.org/gems/rubyserial
Other
154 stars 27 forks source link

Using blocks in gets #32

Closed sergioaugrod closed 8 years ago

sergioaugrod commented 8 years ago

Hello guys,

What do you think of giving the possibility of using blocks in the function gets?

Simple example:

def gets(sep=$/, limit=nil)
  if block_given?
    loop do
      yield(gets_p(sep,limit))
    end
  else
    gets_p(sep, limit)
  end
end

private

def gets_p(sep, limit)
  sep = "\n\n" if sep == ''
  # This allows the method signature to be (sep) or (limit)
  (limit = sep; sep="\n") if sep.is_a? Integer
  bytes = []
  loop do
    current_byte = getbyte
    bytes << current_byte unless current_byte.nil?
    break if (bytes.last(sep.bytes.to_a.size) == sep.bytes.to_a) || ((bytes.size == limit) if limit)
  end

  bytes.map { |e| e.chr }.join
end

Use:

serial.gets do |value|
end

or

serial.gets
deadprogram commented 8 years ago

That seems like a very good and Rubyesque idea. A pull request would be gratefully accepted.