Suppose I have this:
x = %w(greater yellow bandicooot)
And I want to get a specific letter of each string as a string. Of course, I can do something like this (to get the first letter):
x.map { |w| w[0] }.join # => 'gyb'
But I'd like to know whether or not there's a way to do it using just array notation. I've tried this:
x[0][0]..x[-1][0]
Which returns, in this case, the not-so-helpful "g".."b". I could also use array notation like this in this case:
x[0][0] + x[1][0] + x[2][0]
But I'm looking for a non-case-specific solution that doesn't require iteration.
Is there a way to do this strictly with array notation, or is it necessary to do some sort of iteration? And if you can't do it with array notation, is there a better way to do it than using map and join?
Here's a fancy regex way to do it, if you have the word combined in a single space-delimited string:
string = "greater yellow bandicooot"
string.gsub /([^ ])[^ ]* */, '\1'
# => "gyb"
Explanation of the regex:
([^ ]): match group - single nonspace char[^ ]* *: optional sequence of nonspace chars, followed by any optional sequence of space chars.As you can read about here: Ruby regex - gsub only captured group, when using gsub everything in the entire regex is replaced, regardless of if it's in a match group. So you need to use the special variable \1 in the gsub call (must be in a single quoted string, by the way) to refer to the first match group, that you want to use as the output.
I don't believe there is a way to do what you want, but you could do the following.
str = %w(greater yellow bandicooot).join(' ')
#=> "greater yellow bandicooot"
str.gsub(/(?<=\S)./, '')
#=> "gyb"
The regular expression matches any character that is preceded by a non-whitespace character; that is, it matches all characters other than the first character of the string and characters preceded by a whitespace character.
If one is given the string and there could be multiple spaces between words, one could write:
str.squeeze(' ').gsub(/(?<=\S)./, '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With