How can I get a substring from position N to the last char in Ruby?
Just slice the string like:
string[N..-1]
Ruby idiom for substring from index until end of string
I think it isn't.
It seems that Range
is better way to do it.
Extracting the last n characters from a ruby string
Here you have a one liner, you can put a number greater than the size of the string:
"123".split(//).last(5).to_s
For ruby 1.9+
"123".split(//).last(5).join("").to_s
For ruby 2.0+, join returns a string
"123".split(//).last(5).join
Get last character in string
UPDATE:
I keep getting constant up votes on this, hence the edit. Using [-1, 1]
is correct, however a better looking solution would be using just [-1]
. Check Oleg Pischicov's answer.
line[-1]
# => "c"
Original Answer
In ruby you can use [-1, 1]
to get last char of a string. Here:
line = "abc;"
# => "abc;"
line[-1, 1]
# => ";"
teststr = "some text"
# => "some text"
teststr[-1, 1]
# => "t"
Explanation:
Strings can take a negative index, which count backwards from the end
of the String, and an length of how many characters you want (one in
this example).
Using String#slice
as in OP's example: (will work only on ruby 1.9 onwards as explained in Yu Hau's answer)
line.slice(line.length - 1)
# => ";"
teststr.slice(teststr.length - 1)
# => "t"
Let's go nuts!!!
teststr.split('').last
# => "t"
teststr.split(//)[-1]
# => "t"
teststr.chars.last
# => "t"
teststr.scan(/.$/)[0]
# => "t"
teststr[/.$/]
# => "t"
teststr[teststr.length-1]
# => "t"
Ruby - How to select some characters from string
Try foo[0...100]
, any range will do. Ranges can also go negative. It is well explained in the documentation of Ruby.
Getting a substring in Ruby by x number of chars
How about this?
s[0, s.length - 3]
Or this
s[0..-4]
edit
s = "abcdefghi"
puts s[0, s.length - 3] # => abcdef
puts s[0..-4] # => abcdef
Find all indices of a substring within a string
The standard hack is:
indices = "Einstein".enum_for(:scan, /(?=in)/).map do
Regexp.last_match.offset(0).first
end
#=> [1, 6]
Ruby, remove last N characters from a string?
Ruby 2.5+
As of Ruby 2.5 you can use delete_suffix
or delete_suffix!
to achieve this in a fast and readable manner.
The docs on the methods are here.
If you know what the suffix is, this is idiomatic (and I'd argue, even more readable than other answers here):
'abc123'.delete_suffix('123') # => "abc"
'abc123'.delete_suffix!('123') # => "abc"
It's even significantly faster (almost 40% with the bang method) than the top answer. Here's the result of the same benchmark:
user system total real
chomp 0.949823 0.001025 0.950848 ( 0.951941)
range 1.874237 0.001472 1.875709 ( 1.876820)
delete_suffix 0.721699 0.000945 0.722644 ( 0.723410)
delete_suffix! 0.650042 0.000714 0.650756 ( 0.651332)
I hope this is useful - note the method doesn't currently accept a regex so if you don't know the suffix it's not viable for the time being. However, as the accepted answer (update: at the time of writing) dictates the same, I thought this might be useful to some people.
Get substring after the first = symbol in Ruby
Not exactly .after
, but quite close to:
string.partition('=').last
http://www.ruby-doc.org/core-1.9.3/String.html#method-i-partition
Select all characters in a string until a specific character Ruby
You can avoid creating an unnecessary Array (like Array#split
) or using a Regex (like Array#gsub
) by using.
a = "2.452811139617034,42.10874821716908|3.132087902867818,42.028314077306646|-0.07934861041448178,41.647538468746916|-0.07948265046522918,41.64754863599606"
a[0,a.index('|')]
#=>"2.452811139617034,42.1087482171"
This means select characters at positions 0 up to the index of the first pipe (|
). Technically speaking it is start at position 0 and select the length of n where n is the index of the pipe character which works in this case because ruby uses 0 based indexing.
As @CarySwoveland astutely pointed out the string may not contain a pipe in which case my solution would need to change to
#to return entire string
a[0,a.index('|') || a.size]
# or
b = a.index(?|) ? a[0,b] : a
# or to return empty string
a[0,a.index('|').to_i]
# or to return nil
a[0,a.index(?|) || -1]
Related Topics
Carrierwave Fog Amazon S3 Images Not Displaying
How to Transfer Files Using Ssh and Scp Using Ruby Calls
Convert 12 Hr Time to 24 Hr Format in Ruby
Rails Redirect_To :Back Not Working
Active Admin: Sorting on Multiple Columns
Ruby Time Object Converted from Float Doesn't Equal to Orignial Time Object
Attempting to Install Libv8, "Failed to Build Gem Native Extension"
How to Sort Not Simple Hash (Hash of Hashes)
How to Make a Before_Save Conditional
Ruby Imap Idle Concurrency - How to Tackle
Rails Change Routing of Submit in Form_For
Ruby: Eval with String Interpolation
Alias_Method and Class_Methods Don't Mix
Delete Non-Utf Characters from a String in Ruby
How to Test Instance Variable Was Instantiated in Controller with Rspec
Rails 4 Strong Parameters Failing When Creating Instances in Rails Console
Rails - Paperclip Validating Attachment Size When It Shouldn't Be
Invoke Delayed_Job Capistrano Tasks Only on Specific Servers