To count the number of spaces at the beginning and end of string s
I do:
s.index(/[^ ]/) # Number of spaces at the beginning of s
s.reverse.index(/[^ ]/) # Number of spaces at the end of s
This approach requires the edge case when s
contains spaces only to be handled separately.
Is there a better (more elegant / efficient) method to do so?
s.split(s.strip).first.size
s.split(s.strip).last.size
you could also do
beginning_spaces_length , ending_spaces_length = s.split(s.strip).map(&:size)
You could do it at once:
_, spaces_at_beginning, spaces_at_end = /^( *).*?( *)$/.match(s).to_a.map(&:length)
Definitely not more elegant though.
I don't know if it is more efficient, but this works as well.
s.count(' ') - s.lstrip.count(' ')
s.count(' ') - s.rstrip.count(' ')
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