ROR + Replace the last character by detecting it using ruby code by another character
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 "", otherwi开发者_开发知识库se 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 !!!
Much simpler:
text.chomp!('-')
chomp already includes the if condition: if the character exists at the end of the string, it is removed.
> a = "abc-"
=> "abc-"
>> a.chop! if a[-1] == 45 # if last character is a minus sign chop it off
=> 45
>> a
=> "abc"
try the following
text.chop! if text[text.length-1,1] == "-"
text.chop! removes the last character and saves it to the same object
精彩评论