Manage command line 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, using OptionParser I made a cat that will set the stream if the switch is set --upcase:

#!/usr/bin/env ruby

require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: cat [options] [file ...]"

  opts.on("-u", "--upcase", "Upcase stream") do
    options[:upcase] = true
  end
end.parse!

if options[:upcase]
  puts ARGF.read.upcase
else
  puts ARGF.read
end

How can I handle this switch without a block if..else?

.

-1
2

,

#!/usr/bin/env ruby
require 'optparse'

options = { :transform => :itself }
OptionParser.new do |opts|
  opts.banner = "Usage: cat [options] [file ...]"
  opts.on("-u", "--upcase", "Upcase stream") do
    options[:transform] = :upcase
  end
  # add more options for downcase, reverse, etc ...
end.parse!

puts ARGF.read.send(options[:transform])

, , .

?

  • :transform
  • : :itself
  • :upcase
  • send

if , , . , , , , , , .

,

  • max
  • min
  • Hash#fetch
  • Enumerable#detect
  • Enumerable#select
  • Enumerable#chunk
  • Enumerable#drop_while
  • Enumerable#slice_when
  • Enumerable#take_while
  • ....

- for .

for , , "" Ruby.

for if,

str = 'This is an example to be aligned to both margins'    
words = str.split
width, remainder = (50 - words.map(&:length).inject(:+)).divmod(words.length - 1)
words.take(words.length - 1).each { |each| width.times { each << 32 }}
words.take(words.length - 1).shuffle.take(remainder).each { |each| each << 32 }
p words.join
# => "This  is an example to  be aligned to both margins"
+3

- , . . , options[:upcase] . , , .

else if, , , , .

data = ARGF.read;
data.upcase! if options[:upcase];
+1

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


All Articles