bob.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Bob

  def self.hey(remark)
    case remark
    when nothing?
      'Fine. Be that way!'
    when yell?
      'Whoa, chill out!'
    when question?
      'Sure.'
    else
      'Whatever.'
    end
  end

  private

  def self.question?
    -> (r) { r[-1] == '?' }
  end

  def self.yell?
    lambda do |r|
      r = r.delete('^A-Za-z')
      return false if r.empty?

      r.split('').all? { |c| /[[:upper:]]/.match(c) }
    end
  end

  def self.nothing?
    -> (r) { r.strip.size.zero? }
  end

end

Comments

Did some experimenting using Lambdas in when statements.

I really like this kind of approach since I can call the method without passing remark as an argument. Otherwise, calling a class method and passing the remark it as an argument while there is a case remark at the top seems very redundant.

I would love to know if there is a better approach for this.

BigChief45 commented 9 June 2017 at 08:24 UTC

This looks good. The use of lambdas is neat.

That said, some things to think about:

The cure (complicating the categorisation methods) might be worse than the disease (a little bit of redundancy.)

I can call the method without passing remark as an argument. Otherwise, calling a class method and passing the remark it as an argument while there is a case remark at the top seems very redundant.

Might that mean that the case statement is not formulated ideally? Is the code you're trying to write:

1
2
3
4
case remark.type
when :nothing
when :yell
when :question

?

What does OO design have to say about switching on the type of an object?

What happens when you want to add a new condition?

It would be nice if we could follow the Open/Closed principle and be able to do it without needing to modify the hey method. (This may require a different approach.)

Insti commented 9 June 2017 at 09:36 UTC

I have at least one solution using lambda or Procs myself (I haven't looked lately), but I know I did for Bob.

kotp commented 10 June 2017 at 01:15 UTC

You're not logged in right now. Please login via GitHub to comment