How to get strings which are separated with a | or , - ruby

Say I have a string like a|b|c|d ... or like a,b,c,d... I want to extract a b c and d and push it in an array. What's the efficient way of doing it?
So, the input is a|b|c|d or a,b,c,d and the output should be [a,b,c,d].

The split method is what you are looking for.
For example, if you want to split a string into an array of strings separated with the | character, you can do this:
"a|b|c|d".split('|')
=> ["a", "b", "c", "d"]
If you want to split by the string by , or |, you can use the same method with a regular expression:
"a|b|c|d".split(/\||,/)
"a,b,c,d".split(/\||,/)
=> ["a", "b", "c", "d"]

Use the split function.
MyString.split("|")

Related

Get sequence in original format in freemarker

I have defined a sequence like so:
<#assign seq = ["A", "B", "C", "D", "E"]>
I can do: <#list seq[0..] as i>${i}</#list> which will generate an output of ABCDE
Is it possible to get the sequence back in the original format? I.e. ["A", "B", "C", "D", "E"]
For reference, I am using this to first assign an empty sequence and then elements items into it. I want to get the full sequence at the end in the original sequence format because it will be part of a JSON.
There's nothing specialized on that, but you can do this (not sure what escaping syntax you need though, so here I used JSON):
[<#list seq as it>"${it?json_string}"<#sep>, </#list>]
This will return back the original sequence format:
<#assign seq = ["A", "B", "C", "D", "E"]>
[<#list seq[0..] as i><#if i?has_next>"${i}",<#else>"${i}"</#if></#list>]

How do I split a string without keeping the delimiter?

In Ruby, how do I split a string and not keep the delimiter in the resulting split array? I though tthis was the default, but when I try
2.4.0 :016 > str = "a b c"
=> "a b c"
2.4.0 :017 > str.split(/([[:space:]]|,)+/)
=> ["a", " ", "b", " ", "c"]
I see the spaces included in my result. I would like the result to simply be
["a", "b", "c"]
From the String#split documentation:
If pattern contains groups, the respective matches will be returned in the array as well.
Answering your explicitly stated question: do not match the group:
# ⇓⇓ HERE
str.split(/(?:[[:space:]]|,)+/)
or, even without groups:
str.split(/[[:space:],]+/)
or, in more Rubyish way:
'a b, c,d e'.split(/[\p{Space},]+/)
#⇒ ["a", "b", "c", "d", "e"]
String#splitsplits on white-space by default, so don 't bother with a regex:
"a b c".split # => ["a", "b", "c"]
Try this please
str.split(' ')

Splitting a string into an array ruby

I am trying to turn this string
"a,bc,c"
into this array..
["a", "b", "c"]
I've used split on the comma & iterated through it but I'd like to find a cleaner way.
Thanks!
I will use #scan and #uniq method.
"a, bc,c".scan(/[a-z]/).uniq
# => ["a", "b", "c"]
Here we go, one option:
"a, bc,c".gsub(/\W+/, '').chars.uniq
# Outputs:
=> ["a", "b", "c"]

Format data in string to array?

I need to convert data from a string to an array. The string looks like this:
{a,b,c{1,2,3},d,e,f{11,22,33},g}
The array that I want to receive should look like this:
[a, b, c1, c2, c3, d, e, f11, f22, f33, g]
I tried to use the split method but it works poorly.
arr = str.split(' ');
keys = arr[0][2..-2]
keys = keys.split(',')
Do you have any ideas how it could be implemented?
Here's what I'd use:
string = '{a,b,c{1,2,3},d,e,f{11,22,33},g}'
array = string.scan(/[a-z](?:{.+?})?/).flat_map{ |s|
if s['{']
prefix = s[0]
values = s.scan(/\d+/)
([prefix] * values.size).zip(values).map(&:join)
else
s
end
}
array # => ["a", "b", "c1", "c2", "c3", "d", "e", "f11", "f22", "f33", "g"]
Here's how it works:
string.scan(/[a-z](?:{.+?})?/) # => ["a", "b", "c{1,2,3}", "d", "e", "f{11,22,33}", "g"]
returns the string broken into chunks, looking for a single letter followed by an optional string of { with some text then }.
values = s.scan(/\d+/) # => ["1", "2", "3"], ["11", "22", "33"]
As it's running in flat_map, if { is found, the numbers are scanned out.
([prefix] * values.size).zip(values).map(&:join) # => ["c1", "c2", "c3"], ["f11", "f22", "f33"]
And then an array of the prefix, with the same number of elements as there are values is created and zipped together, resulting in:
[["c", "1"], ["c", "2"], ["c", "3"]], [["f", "11"], ["f", "22"], ["f", "33"]]
The join glues those sub-arrays together. And flat_map flattens any subarrays created so the resulting output is a single array.
You need to arr = str.split(',') in the first step, because there is no whitespace between the values.
Also keep in mind you have {} to handle too.
This worked for me with simple regex and gsubing (though Tin Man's solution is better ruby):
def my_string_to_array(input_string)
groups = input_string.scan(/\w+\{.*?\}/)
groups.each do |group|
modified = group.gsub(',', ",#{group.match(/\w+/)[0]}").delete("{}")
input_string.gsub!(group, modified)
end
created_array = input_string.delete("{}").split(',')
end
string = '{a,b,c{1,2,3},d,e,f{11,22,33},g}'
my_string_to_array(string)
=> ["a", "b", "c1", "c2", "c3", "d", "e", "f11", "f22", "f33", "g"]
The way it works is that it first finds the groups having alphabets followed by braces and digits (like c{1,2,3})
For each such group, it modifies it by gsubing ',' with ',<alphabet>' and removing the braces.
Next, it replaces these groups with the modified ones in the original string.
And finally it removes the starting and ending braces in the original string, and converts it into an array.

Ruby one liner to pass arrays elements into a string with separator

I have an array like this:
myarray = ['value1','value2','value3']
And I'm looking for a one element array like this:
mynewarray = ['value1|value2|value3']
I know how to do that using each and concatening in a string, but I'm wondering if there is a oneliner and beautiful Ruby way of doing so...
You can use the Array#join method.
myarray.join('|')
Array#join doc:
Returns a string created by converting each element of the array to
a string, separated by sep.
[ "a", "b", "c" ].join #=> "abc"
[ "a", "b", "c" ].join("-") #=> "a-b-c"
Howsabout...
mynewarray = [myarray.join('|')]
Here you go:
[myarray.join('|')]
That should do it.
You can try next:
[myarray.join("|")]
[[ "a", "b", "c" ]*'|']
will output
["a|b|c"]
"aa|bb|cc".scan(/[^\|]+/)
will output
["aa", "bb", "cc"]
with Ruby 1.9.x

Resources