views:

53

answers:

3

Is it possible to detect the last character of string in ruby on rails and replace it by "". Explanation :: Suppose I have string as "demo-" then i have to check its last character, If it is "-" then replace it by "", otherwise no action should be taken.

Example - Code ::

search_text.downcase! if !search_text.nil?

now if seach_text have value as "demo-" then change it to "demo" by replacing "-".

Thanks in Advance !!!

A: 

try the following

text.chop! if text[text.length-1,1] == "-"

text.chop! removes the last character and saves it to the same object

should be `text[text.length - 1, 1]` or `text[-1, 1]`
tig
@tig my bad. now changed it.
Thanx buddy, It works... I found alternate option to solve my problem rather than this one. but this is fine one...
Rahul Patil
You could share the alternate option here if you can :)
Friend actually In first step, I am accessing value from string, but now I am using array for this. so my problem was solve by using zeroth value of array.
Rahul Patil
Dude, Your method is quite lengthy in code and complicated. Please see the below code of Mark. Really very much helpful.
Rahul Patil
A: 
> a = "abc-"
=> "abc-"
>> a.chop! if a[-1] == 45 # if last character is a minus sign chop it off
=> 45
>> a
=> "abc"
is not it better to use `a[-1, 1] == '-'`?
tig
@tig, could you explain why? is it clearer? i was going for brevity as long as the operation is pretty simple
I guess it is because of converting character to char code. "-" is better for eyes than a 45
+6  A: 

Much simpler:

text.chomp!('-')

chomp already includes the if condition: if the character exists at the end of the string, it is removed.

Mark Thomas
Thanx buddy, really this method is quite very helpful.
Rahul Patil