How to split a string in Ruby and get all items except the first one?
Try this:
first, *rest = ex.split(/, /)
Now first
will be the first value, rest
will be the rest of the array.
Split a string and remove the first element in string
The 'split' method works in this case
https://apidock.com/ruby/String/split
'4.0.0-4.0-M-672092'.split('-')[1..-1].join('-')
# => "4.0-M-672092"
Just be careful, in this application is fine, but in long texts this might become unoptimized, since it splits all the string and then joins the array all over again
If you need this in wider texts to be more optimized, you can find the "-" index (which is your split) and use the next position to make a substring
text = '4.0.0-4.0-M-672092'
text[(text.index('-') + 1)..-1]
# => "4.0-M-672092"
But you can't do it in one line, and not finding a split character will result in an error, so use a rescue statement if that is possible to happen
Split string by every first space in ruby
Maybe using scan
would give you your expected output easier:
p str.scan(/[A-Z]+|\s{3}/)
# ["AB", "C", " ", "D", "E", " ", "F"]
As your input is only capitalized characters, [A-Z]
would work, /[a-z]/i
is for both cases.
Wondering why such an output:
p str.scan(/[A-Z]+|\s{3}/).map(&:split)
# [["AB"], ["C"], [], ["D"], ["E"], [], ["F"]]
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]
How to count length after split in ruby except some values inside the string?
Think in terms of receivers. You send split
to a string and it returns an array. You then send length
to that array:
str.split(',')
#=> ["a", "3", "b", "c", "0"]
str.split(',').length
#=> 4
So in order to exclude '0'
, you could create an array that doesn't contain the unwanted elements and call length
on that array: (e.g. via difference
)
str.split(',').difference(['0'])
#=> ["a", "3", "b", "c"]
str.split(',').difference(['0']).length
#=> 4
or you could call count
and specify to only count elements that are not '0'
:
str.split(',').count { |x| x != "0" }
#=> 4
What is the best way to split a string to get all the substrings by Ruby?
def split_word s
(0..s.length).inject([]){|ai,i|
(1..s.length - i).inject(ai){|aj,j|
aj << s[i,j]
}
}.uniq
end
And you can also consider using Set
instead of Array for the result.
PS: Here's another idea, based on array product:
def split_word s
indices = (0...s.length).to_a
indices.product(indices).reject{|i,j| i > j}.map{|i,j| s[i..j]}.uniq
end
How to split string into only two parts with a given character in Ruby?
String#split takes a second argument, the limit.
str.split(' ', 2)
should do the trick.
Get string except first sentence
- i = article.content.index('.')
= article.content[0..i-1] # title
= article.content[i+1..-1] # content
Best way to split an array of strings in ruby?
You need map{...}
, not map(...)
for correct syntax in Ruby here:
array = ["string_apple", "string_banana", "string_orange"]
# Assign to a different array:
split_array = array.map{ |s| s.split(/_/) }
# Or modify the original array in place:
array.map!{ |s| s.split(/_/) }
# [["string", "apple"], ["string", "banana"], ["string", "orange"]]
How to split the first and the last element on a Ruby string?
Is this what you want to do?
first, *_, last = "now is the time for all".split
first #=> "now"
last #=> "all"
Related Topics
Find Records with Datetime That Match Today's Date - Ruby on Rails
How to Access a Ruby Module Method
Is Ruby a Scripting Language or an Interpreted Language
Convert JSON String to JSON Array in Rails
Starting or Restarting Unicorn with Capistrano 3.X
Ruby Easy Search for Key-Value Pair in an Array of Hashes
How to Split String Across New Lines and Keep Blank Lines
Rbenv Build Failed on Ubuntu 14.04
How to Validate Associated Model Id
What Is the Send() Method Used For
Rails: How to Show User's "Last Seen At" Time
Passing Param Values to Redirect_To as Querystring in Rails
Checking If a Method Is Defined on the Class