Jeremy Thomas
Jeremy Thomas

Reputation: 6694

How to write single line blocks

I find myself trying to use single line blocks but end up having to break up into multiple lines anyway. My most recent example is that I'm trying to get initials from the name field of an active record object.

@employee.name = "John Doe"

and I want to return "JD".

The only way I knew how to do it was to initialize a string, then split the name, then add to the initialized string. At the very least how can I avoid having to initialize the empty string?

def initials # In model
    intials = ''
    name_array = self.name.split(" ")
    name_array.each  { |name| initials += name[0].capitalize }
    return initials
end

Upvotes: 2

Views: 128

Answers (2)

the Tin Man
the Tin Man

Reputation: 160611

I'd try things like:

'John Doe'.scan(/\b[A-Z]/).join # => "JD"
'John Doe'.scan(/\b[a-z]/i).join # => "JD"

Any of these sort of expressions can break down with names with sufficient complexity:

'John Doe-Smith'.scan(/\b[a-z]/i).join # => "JDS"
'John Doe Jr. III'.scan(/\b[a-z]/i).join # => "JDJI"
'Dr. John Doe MD'.scan(/\b[a-z]/i).join # => "DJDM"

Then it becomes a case of needing to strip out the parts that you don't want.

Upvotes: 2

Krzysztof Safjanowski
Krzysztof Safjanowski

Reputation: 7438

Let me play with some proof of concept

class Employee 
  attr_accessor :name

  def initials
    @name.split(' ').map { |name| name[0] }.join
  end
end

e = Employee.new
e.name = "Foo Baz"
p e.initials # FB

Upvotes: 3

Related Questions