Code_today

Today I’ve been doing this:

# Let's say you have this data from an
# external command. You want to collect it.
out = <<-OUT

Width: 300
Height: 500
PosX: 40
PosY: 35

Modules in use: one, two, five
Process ID: 33178

OUT

p out.lines(chomp: true).reject { it[/^\s*$/] }.map { it.split(': ')
  .then {|k,v| [k.tr(' ',''), (Integer(v) rescue v)]}}.to_h

# {
#   "Width" => 300,
#   "Height" => 500,
#   "PosX" => 40,
#   "PosY" => 35,
#   "Modulesinuse" => "one, two, five",
#   "ProcessID" => 33178
# }



# another way
p out.lines(chomp: true).inject({}) {|h,ln|
  h[$1.tr(' ', '')] = (Integer($2) rescue $2) if ln[/^([^:]+): (.*)$/]; h
}

# {
#   "Width" => 300,
#   "Height" => 500,
#   "PosX" => 40,
#   "PosY" => 35,
#   "Modulesinuse" => "one, two, five",
#   "ProcessID" => 33178
# }

Then I started looking at the method grep.
I found arr.grep(Integer).grep(2..6) ugly. I wanted multi-grep or mgrep.


ar = [1,2,3,4,6,8,11,'a']

p ar.grep(Integer).grep(2..6) # => [2, 3, 4, 6]



class Array
  def mgrep(*args)
    args.inject(self) {|s,a| s.grep(a) }
  end
end

p ar.mgrep(Integer, 2..6) # => [2, 3, 4, 6]

(I put the method in the Array class here)