Created
December 21, 2014 18:48
-
-
Save madrobby/27b537ab0344c827daf8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
letters = "" | |
letters << user.first_name[0,1] if user.first_name.size > 1 && 'A'..'Z'.include?(user.first_name[0,1].upcase) | |
letters << user.last_name[0,1] if user.last_name.size > 1 && 'A'..'Z'.include?(user.last_name[0,1].upcase) |
Or the official MapReduceTM version:
letters = [user.first_name, user.last_name].select {|field|
field.present? && field =~ /\A[a-z]/i
}.map {|chosen|
chosen[0]
}.join
@prakashmurthy thanks!
@henning-koch, @jarkko: The original is pretty easy to read, yeah. I might just go with the extra parens.
@mikebowler: interesting approach that avoids the loop, thanks!
Took a stab and combined @jarkko's approach with the original that doesn't use regular expressions:
letters = [user.first_name, user.last_name].map do |part|
part[0,1] if part.present? && ('A'..'Z').include?(part[0,1].upcase)
end.join
Nice ruby puzzle ;-). What about String#[]
with a regex capture group? The dot in the regex enforces the length to be >= 2.
letters = [user.first_name, user.last_name].map { |name| name[/^([a-z])./i, 1] }.compact
I would write it like this:
letters = [first_name, last_name].map { |x| x[0] if ('A'..'Z').include?(x[0]) }.join
@lrz Yeah, basically what I ended up with. Note that I have an extra test because first/last name could be nil.
letters = "#{first_name[0]}#{last_name[0]}".gsub(/[^A-Z]/, '')
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like @jarkko's solution for its non-cleverness.