On Mon, Mar 29, 2010 at 8:41 PM, Jesse B. [email protected] wrote:
How would I find the number of spaces at the beginning of a line before
the occurrance of the first non-space character?
Would the best method be to use a regular expression that covers all
non-space characters and get the index of the first occurrance of that?
Posted via http://www.ruby-forum.com/.
Hi, a quick appraisal of the issues with previous solutions.
This solution counts non-leading spaces
i = 0
" hello ".chars.to_a.each do |c|
i+=1 if( c == " " )
end
This one returns nil if there is not text after the leading whitespaces.
str =~ /\S/
Each of these count non-space whitespaces (ie " \t hello" would be 3
instead
of 1 )
s.index(%r{\S})
str[/\A\s*/].length
s =~ /(\s*)/
$1.length
So here is a quick suite you can use to test the solutions, along with a
solution which passes. If this suite doesn’t accurately reflect what you
were trying to do, modify it and re-post You’ll be a lot more likely
to
get a solution which does explicitly what you are looking for, and maybe
find some areas that are ambiguous in your question, such as multi-line
strings, and strings with mixtures of whitespace types.
require ‘test/unit’
def leading_spaces( str )
fill this out however you like, my solution is:
str =~ /[^ ]/ || str.length
end
class TestLeadingSpaces < Test::Unit::TestCase
def test_one_space
assert_equal 1 , leading_spaces(’ ')
end
def test_empty_string
assert_equal 0 , leading_spaces(‘’)
end
def test_two_leading_spaces
assert_equal 2 , leading_spaces(’ hello’)
end
def test_no_spaces
assert_equal 0 , leading_spaces(‘hello’)
end
def test_spaces_inside_but_not_leading
assert_equal 0 , leading_spaces(‘hello there’)
end
def test_spaces_inside_and_leading
assert_equal 2 , leading_spaces(’ hello there’)
end
def test_trailing_spaces_not_leading
assert_equal 0 , leading_spaces('hello ')
end
def test_trailing_spaces_and_inside
assert_equal 0 , leading_spaces('hello there ')
end
def test_spaces_everywhere
assert_equal 1 , leading_spaces(’ hello there ')
end
def test_mixture_of_spaces_and_tabs
assert_equal 1 , leading_spaces(" \t hello")
end
the following are not really defined in the question, this is what I
think the OP is asking for
might also be asking for an array listing the indentions for each
line?
def multi_line_spaces
assert_equal 6 , leading_spaces(<<-MULTI_LINE_STRING)
this is six spaces
this is eight
MULTI_LINE_STRING
end
end