Rails split by last delimiter [duplicate] - ruby-on-rails

This question already has answers here:
Ruby: Split string at character, counting from the right side
(6 answers)
Closed 9 years ago.
I want to be able to split strings into 2 elements, because each string would contain at least one delimiter.
Example: "hello_world". If I apply .split("_") then I receive: ["hello", "world"].
The problem arises when I have a string with two or more delimiters. Example "hello_to_you".
I want to receive: ["hello_to", "you"].
I know about the limit option for the split function: .split("_", 2), but it produces: ["hello", "to_you"].
So, basically, I would need to split the entire string ONLY with the last delimiter ("_").

This is exactly what String#rpartition does:
first_part, _, last_part = 'hello_to_you'.rpartition('_')
first_part # => 'hello_to'
last_part # => 'you'

try
'hello_to_you'.split /\_(?=[^_]*$)/

class String
def split_by_last_occurrance(char=" ")
loc = self.rindex(char)
loc != nil ? [self[0...loc], self[loc+1..-1]] : [self]
end
end
"test by last_occurrance".split_by_last #=> ["test by", "last"]
"test".split_by_last_occurrance #=> ["test"]

Related

How do I split a string on a certain character in lua? [duplicate]

This question already has answers here:
Split string in Lua?
(18 answers)
Closed 2 years ago.
I'm trying to split a string on a space in Lua. What I mean is if i had a string named "str" and it was equal to "hello world",
str = "hello world"
it should somehow return the string "world" because it is after the space. How do I do this?
if you want to take only the first value before the first space:
local result = str:match("%w+")
print(result)
if you want to collect each of the elements separated by space:
local tb = {}
for i in str:gmatch("%w+") do
print(i)
table.insert(tb, i) -- in case you want to store each separate element in a table
end

Rails, select last n characters from a string? [duplicate]

This question already has answers here:
Extracting the last n characters from a ruby string
(9 answers)
Closed 7 years ago.
I have a string "foo bar man chu" and I want to select the last 5 characters from it.
The regex expression /.{5}$/ does the job of selecting them, but how do I save them to a string in Rails? gsub(/.{5}$/,'') removes them, kind of the opposite of what I want. Thanks!
The match method will return the result of attempting to match the string with the regular expression
result = "foo bar man chu".match(/.{5}$/)
puts result
=> "n chu"
If the regular expression is not matched, then nil will be returned.

I am having the string , i have to convert it into hash like no 2 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here's my code:
1. "special_filter,|filter_str,(&(a=1)(c=11)(p=c=11,o=m,d=4))"
2.{ "a" =>"1", "c" => "11" , "p" => "c=11,o=m,d=4"}
#!/usr/bin/ruby
string = "special_filter,|filter_str,(&(a=1)(c=11)(p=c=11,o=m,d=4))"
hash = {}
string.slice(/\(&.*\)/).split(")").each do |match|
match.tr("(&","").split("=",2).each_slice(2) { |key, value| hash[key] = value }
end
Line by line:
Line 1: Set a variable, string, with the starting string.
string = "special_filter,|filter_str,(&(a=1)(c=11)(p=c=11,o=m,d=4))"
Line 2: Set a variable, hash, with an empty hash to fill.
hash = {}
Line 3:
Cut out the portion of the string that matches this regexp
string.slice(/\(&.*\)/) => "(&(a=1)(c=11)(p=c=11,o=m,d=4))"
The regexp is bookended with forward slashes (/regexp goes here/).
Parentheses have special meaning in regex, so they must be escaped with backslashes.
The & matches the & in the string.
In regex, a . means any character.
* means none to unlimited of the preceding character.
So this regex matches (&) as well as (&fjalsdkfj).
Split the string by right parentheses
string.slice(/\(&.*\)/).split(")") => ["(&(a=1", "(c=11", "(p=c=11,o=m,d=4"]
Then iterate through the array of results
string.slice(/\(&.*\)/).split(")").each do |match|
Line 4:
Take the iteration and remove unwanted characters from it
match.tr("(&","")
Split it one time, using the first = sign
match.tr("(&","").split("=",2)
Use the 2 value array as a key and value on the hash
match.tr("(&","").split("=",2).each_slice(2) { |key, value| hash[key] = value }
My try to this.
Hash[*string[/\&.*/].tr("&(","").split(")").map{|i| i.split("=",2)}.flatten]
Some ideas taken from #Conner's solution ;)
Thanks #corner I was able to know some functions i never used before.

How to split string into 2 parts after certain position

For example I have some random string:
str = "26723462345"
And I want to split it in 2 parts after 6-th char. How to do this correctly?
Thank you!
This should do it
[str[0..5], str[6..-1]]
or
[str.slice(0..5), str.slice(6..-1)]
Really should check out http://corelib.rubyonrails.org/classes/String.html
Here’s on option. Be aware, however, that it will mutate your original string:
part1, part2 = str.slice!(0...6), str
p part1 # => "267234"
p part2 # => "62345"
p str # => "62345"
Update
In the years since I wrote this answer I’ve come to agree with the commenters complaining that it might be excessively clever. Below are a few other options that don’t mutate the original string.
Caveat: This one will only work with ASCII characters.
str.unpack("a6a*")
# => ["267234", "62345"]
The next one uses the magic variable $', which returns the part of the string after the most recent Regexp match:
part1, part2 = str[/.{6}/], $'
p [part1, part2]
# => ["267234", "62345"]
And this last one uses a lookbehind to split the string in the right place without returning any extra parts:
p str.split(/(?<=^.{6})/)
# => ["267234", "62345"]
The best way IMO is string.scan(/.{6}/)
irb(main)> str
=> "abcdefghijklmnopqrstuvwxyz"
irb(main)> str.scan(/.{13}/)
=> ["abcdefghijklm", "nopqrstuvwxyz"]
_, part1, part2 = str.partition /.{6}/
https://ruby-doc.org/core-1.9.3/String.html#method-i-partition
As a fun answer, how about:
str.split(/(^.{1,6})/)[1..-1]
This works because split returns the capture group matches, in addition to the parts of the string before and after the regular expression.
Here's a reusable version for you:
str = "26723462345"
n = str.length
boundary = 6
head = str.slice(0, boundary) # => "267234"
tail = str.slice(boundary, n) # => "62345"
It also preserves the original string, which may come in handy later in the program.

Array to single string [duplicate]

This question already has answers here:
Array.join("\n") not the way to join with a newline?
(7 answers)
Closed 5 years ago.
I'm having an issue which I can't seem to solve. I have an array which I need to convert to an single string. The elements need to be put underneath each other.
sample_array = ['a','b','c','d','e']
desired output:
sample_array = "a
b
c
d
e"
I thought I could do this with a 'heredoc', but I can only get the elements behind each other inline. This is unfortunately not what I need. Anyone who can help me?
edit for edit question
In a single line, you can use inject:
sample_array = ['a','b','c','d','e']
puts sample_array.inject(""){|conc,x| conc + "\n" + x }
=> "a b c d e"
that will fold the array recursively and adding a line between chars

Resources