ARGV handle in Ruby without if ... else block

In a blog post on unconditional programming, Michael Perot shows how bounding operators ifcan be used as a tool to reduce code complexity.

He uses a concrete example to illustrate his point. Now I was thinking of other specific examples that could help me learn more about unconditional / ifless / forless programming.

For example, this cat has a block if..else:

#!/usr/bin/env ruby

if ARGV.length > 0
  ARGV.each do |f|
    puts File.read(f)
  end
else
  puts STDIN.read
end

It turns out that ruby ​​has ARGF, which makes this program much easier:

#!/usr/bin/env ruby

puts ARGF.read

I am wondering if there exists ARGFhow to handle the above example so that there is no block if..else?

.

+4
3

(, ), . . , if/elsif/else, .

, . , - , - , . , , . , , .

, , , - ARGV, STDIN, .

io = ARGV.map { |f| File.new(f) };
io = [STDIN] if !io.length;

, , io.

, if/else , , : . , , , . .

# I don't have a really good name for this, but it a
# common enough idiom. Perl provides the same feature as <>
def arg_files
    return ARGV.map { |f| File.new(f) } if ARGV.length;
    return [STDIN];
end

, , cat stdin .

arg_files.each { |f| puts f.read }
-1

,

inputs = { ARGV => ARGV.map { |f| File.open(f) }, [] => [STDIN] }[ARGV]
inputs.map(&:read).map(&method(:puts))

.

?

  • .
  • ARGV
  • [] STDIN, ARGV,
  • ARGV , [STDIN],

.

, - if , . if.

+1

-, , , , , , .

, monkeypatch String STDIN 1, STDIN, -1 (), .

class String
  def read
    File.read self if File.exist? self
  end
end

puts [*ARGV, STDIN][0..ARGV.length-1].map{|a| a.read}

- , if, , , , , , .

EDIT: , http://blog.jayfields.com/2008/04/alternatives-for-redefining-methods.html http://www.justinweiss.com/articles/3-ways-to-monkey-patch-without-making-a-mess/

String, , , , ,

module ReadString
  def read
    File.read self if File.exist? self
  end
end

class String
  include ReadString
end

EDIT: just read about the safe path to the monkey patch, for your documentation see https://solidfoundationwebdev.com/blog/posts/writing-clean-monkey-patches-fixing-kaminari-1-0-0-argumenterror-comparison- of-fixnum-with-string-failed? utm_source = rubyweekly & utm_medium = email

-2
source

Source: https://habr.com/ru/post/1664936/


All Articles