Problem with removing letters from string
-
How can I remove the first four letters of a string?
Here is a test that is giving me strange result...
a = "hello there"
a[1] #=> "101"I was expecting this...
a = "hello there"
a[1] #=> "e"What I am doing wrong?
-
This one seems to work.
a = "hello there"
a[1,1] #=> "e" -
@renderiza said:
How can I remove the first four letters of a string?
Here is a test that is giving me strange result...
a = "hello there"
a[1] #=> "101"I was expecting this...
a = "hello there"
a[1] #=> "e"What I am doing wrong?
a[1] returns the character in the second position of the string, and in the version of Ruby embedded in SketchUp a character is displayed as its numeric value, not its ASCII representation. You can use a[1].chr to get a string containing the ASCII.
In your second example, a[1,1] is a length 1 slice from the string, which is also a string (not a character) so it displays as a string.
-
Be careful, ... in Ruby 1.9+ they changed the
[ ]
method to return what we all expect an index to return.try using a range:
a = "hello there" b = a[4..-1] %(#804000)[>> "o there"]
-
thank you guys!
Here is what I ended up using to eliminate first four letters...
"sting"[4,100] #=> "g"
-
I would recommend you use Dan suggestions as it's always correct. You example will fail when you feed it a string that's over 100 characters. And it's not a good practice to give out of range values.
-
@tt_su said:
I would recommend you use Dan suggestions as it's always correct. You example will fail when you feed it a string that's over 100 characters. And it's not a good practice to give out of range values.
Will replace the code to Dan is suggestion for the next update of "Rename by Layer" plugin.
Thanks!
-
BUT be aware that non-ASCII accented characters etc are actually 'two-bits'...
So then
**a = "héllo there"** héllo there **b = a[4..-1]** lo there
BUT all is not lost:
**a = "hello there" b = a.split('')** ["h", "e", "l", "l", "o", " ", "t", "h", "e", "r", "e"]
AND
**a = "héllo there" b = a.split('')** ["h", "é", "l", "l", "o", " ", "t", "h", "e", "r", "e"]
SO THEN
**b = a.split('')[4..-1].join('')** o there
should do it, even with strings containing non-ASCII characters -
@tig said:
should do it, even with strings containing non-ASCII characters
Interesting -
split
uses regex functions, which is to an extent in Ruby 1.8 aware of Unicode. -
@tig said:
SO THEN
**b = a.split('')[4..-1].join('')** o there
should do it, even with strings containing non-ASCII charactersGreat advice!...thank you guys!
Advertisement