Ruby array to string conversion - ruby

I have a ruby array like ['12','34','35','231'].
I want to convert it to a string like '12','34','35','231'.
How can I do that?

I'll join the fun with:
['12','34','35','231'].join(', ')
# => 12, 34, 35, 231
EDIT:
"'#{['12','34','35','231'].join("', '")}'"
# => '12','34','35','231'
Some string interpolation to add the first and last single quote :P

> a = ['12','34','35','231']
> a.map { |i| "'" + i.to_s + "'" }.join(",")
=> "'12','34','35','231'"

try this code ['12','34','35','231']*","
will give you result "12,34,35,231"
I hope this is the result you, let me know

array.map{ |i| %Q('#{i}') }.join(',')

string_arr.map(&:inspect).join(',') # or other separator

I find this way readable and rubyish:
add_quotes =- > x{"'#{x}'"}
p ['12','34','35','231'].map(&add_quotes).join(',') => "'12','34','35','231'"

> puts "'"+['12','34','35','231']*"','"+"'"
'12','34','35','231'
> puts ['12','34','35','231'].inspect[1...-1].gsub('"',"'")
'12', '34', '35', '231'

And yet another variation
a = ['12','34','35','231']
a.to_s.gsub(/\"/, '\'').gsub(/[\[\]]/, '')

irb(main)> varA
=> {0=>["12", "34", "35", "231"]}
irb(main)> varA = Hash[*ex.collect{|a,b| [a,b.join(",")]}.flatten]
...

irb(main):027:0> puts ['12','34','35','231'].inspect.to_s[1..-2].gsub('"', "'")
'12', '34', '35', '231'
=> nil

You can use some functional programming approach, transforming data:
['12','34','35','231'].map{|i| "'#{i}'"}.join(",")

suppose your array :
arr=["1","2","3","4"]
Method to convert array to string:
Array_name.join(",")
Example:
arr.join(",")
Result:
"'1','2','3','4'"

array.inspect.inspect.gsub(/\[|\]/, "") could do the trick

Related

get the number from string by regex

I have a string like this:
"com.abcd.efghi.pay.0.99"
"com.abcd.efghi.pay.9.99"
"com.abcd.efghi.pay.19.99"
I want get the number(0.99, 9.99, 19.99). I tried to do like this:
"com.abcd.efghi.pay.0.99".scan(/\d/).join
=> "099"
Anyone can help me get the correct result. Thanks in advance!
"com.abcd.efghi.pay.0.99".split(/\D+/, 2).last # => "0.99"
"com.abcd.efghi.pay.9.99".split(/\D+/, 2).last # => "9.99"
"com.abcd.efghi.pay.19.99".split(/\D+/, 2).last # => "19.99"
or
"com.abcd.efghi.pay.0.99".sub(/\D+/, "") # => "0.99"
"com.abcd.efghi.pay.9.99".sub(/\D+/, "") # => "9.99"
"com.abcd.efghi.pay.19.99".sub(/\D+/, "") # => "19.99"
This is pretty simple, regexp for numbers like 0.00 or 00.00:
\d{1,2}.{2,}
\d Any digit
\d{1,2} Between 1 and 2 of digit
. a dot
\d{2,} 2 or more of digit
Example:
>> "com.abcd.efghi.pay.19.99"[/\d{1,2}.{2,}/, 0]
=> "19.99"
>> "com.abcd.efghi.pay.9.99"[/\d{1,2}.{2,}/, 0]
=> "9.99"
You probably want something like this:
\d+(\.\d+)?
which looks for an integer followed by an optional fractional part.
Something like this:
"com.abcd.efghi.pay.0.99".scan(/(\d+[.]\d+)/).flatten.first
# => "0.99"
Without regex:
str = "com.abcd.efghi.pay.0.99"
str.split(".").last(2).join(".") # => "0.99"
You can use this regex in scan:
\b\d+(?:\.\d+)?
You need to use end of the line anchor.
\b\d+(?:\.\d+)?$
Ah, so many ways. Here are a couple more:
str = "com.abcd.efghi.pay.9.99"
str[str.index(/\d/)..-1] #=> "9.99"
str.sub(/.*?(?=\d)/,'') #=> "9.99"

retrieve numbers from a string with regex

I have a string which returns duration in the below format.
"152M0S" or "1H22M32S"
I need to extract hours, minutes and seconds from it as numbers.
I tried like the below with regex
video_duration.scan(/(\d+)?.(\d+)M(\d+)S/)
But it does not return as expected. Anyone has any idea where I am going wrong here.
"1H22M0S".scan(/\d+/)
#=> ["1", "22", "0']
You can use this expression: /((?<h>\d+)H)?(?<m>\d+)M(?<s>\d+)S/.
"1H22M32S".match(/((?<h>\d+)H)?(?<m>\d+)M(?<s>\d+)S/)
#=> #<MatchData "1H22M32S" h:"1" m:"22" s:"32">
"152M0S".match(/((?<h>\d+)H)?(?<m>\d+)M(?<s>\d+)S/)
#=> #<MatchData "152M0S" h:nil m:"152" s:"0">
Question mark after group makes it optional. To access data: $~[:h].
If you want to extract numbers, you could do as :
"1H22M32S".match(/(?<hour>(\d+))H(?<min>(\d+))M(?<sec>(\d+))S/i).captures
# => ["1", "22", "32"]
"1H22M32S".match(/(?<hour>(\d+))H(?<min>(\d+))M(?<sec>(\d+))S/i)['min']
# => "22"
"1H22M32S".match(/(?<hour>(\d+))H(?<min>(\d+))M(?<sec>(\d+))S/i)['hour']
# => "1"
Me, I'd hashify:
def hashify(str)
str.gsub(/\d+[HMS]/).with_object({}) { |s,h| h[s[-1]] = s.to_i }
end
hashify "152M0S" #=> {"M"=>152, "S"=>0}
hashify "1H22M32S" #=> {"H"=>1, "M"=>22, "S"=>32}
hashify "32S22M11H" #=> {"S"=>32, "M"=>22, "H"=>11}
hashify "1S" #=> {"S"=>1}

'string' to ['s', 'st', 'str', 'stri', 'strin', 'string']

What's the most elegant way of doing
'string'
=> ['s', 'st', 'str', 'stri', 'strin', 'string']
I've been trying to think of a one liner, but I can't quite get there.
Any solutions are welcome, thanks.
How about this?
s = 'string'
res = s.length.times.map {|len| s[0..len]}
res # => ["s", "st", "str", "stri", "strin", "string"]
The more declarative I can come up with:
s = "string"
1.upto(s.length).map { |len| s[0, len] }
#=> ["s", "st", "str", "stri", "strin", "string"]
You can use Abbrev in Standard Library
require 'abbrev'
s = Abbrev::abbrev(['string']).keys
puts s.inspect
I must add the other way to use this after requiring the Abbrev library, with the .abbrev method added to Array:
require 'abbrev'
s = ['string'].abbrev.keys
puts s.inspect
If the order is important to match your return in the question, just call .sort on keys.
s.chars.zip.inject{ |i,j| i << i.last + j.first }
Another variant (this will include the empty string in the result):
s.each_char.inject([""]) {|a,ch| a << a[-1] + ch}
This
starts with an array containing the empty string [""]
for each char ch in the string, appends ch to the last result a[-1] + ch
adds this to the result array
s = "string"
s.each_char.with_object([""]){|i,ar| ar << ar[-1].dup.concat(i)}.drop(1)
#=> ["s", "st", "str", "stri", "strin", "string"]

Ruby Split Integer Into Array

I have this value x = 876885 . I want to split that value into the array like [876,885]
This is what I tried
x.to_s[0..2].split(',') #=> ["876"]
How can I get something like [876,885]?
Similar to DigitalRoss's answer.
x.divmod(1000)
[x/1000, x%1000] # => [876, 885]
How's about this:
x = 876885
x.to_s.scan(/.../).map {|e| e.to_i }
=> [876, 885]
If you want to be able to handle numbers of arbitrary length, then you can do it using each_slice:
876885.to_s.each_char.each_slice(3).map{|x| x.join}
How about this?
[x.to_s[0..2], x.to_s[3..-1]]
#DigitalRoss's solution is the best for 6-digit numbers, but here's a more general one:
a = 876885
a.to_s.chars.each_slice(3).map { |a| a.join.to_i }
# ⇒ [
# [0] 876,
# [1] 885
#]

Ruby regex matching overlapping terms

I'm using:
r = /(hell|hello)/
"hello".scan(r) #=> ["hell"]
but I would like to get [ "hell", "hello" ].
http://rubular.com/r/IxdPKYSUAu
You can use a fancier capture:
'hello'.match(/((hell)o)/).captures
=> ["hello", "hell"]
No, regexes don't work like that. But you can do something like this:
terms = %w{hell hello}.map{|t| /#{t}/}
str = "hello"
matches = terms.map{|t| str.scan t}
puts matches.flatten.inspect # => ["hell", "hello"]
Well, you can always take out common subexpression. I.e., the following works:
r = /hello{0,1}/
"hello".scan(r) #=> ["hello"]
"hell".scan(r) #=> ["hell"]
You could do something like this:
r = /(hell|(?<=hell)o)/
"hello".scan(r) #=> ["hell","o"]
It won't give you ["hell", "hello"], but rather ["hell", "o"]

Resources