Convert ruby array to string - ruby

I'm fairly new to ruby. I have the following csv:
Office (1), Test
Office (Test)(2), Test
In "data.csv".
Then in my ruby script I have;
CSV.foreach("data.csv") do |line|
registeredOffice = line[0].to_s()
macOffice = registeredOffice.scan(/\(([^\)]+)\)/).last
csvText = "#{csvText}\n#{macOffice}"
end
Which gives me
["1"]
["2"]
However I want to know how to convert the above to a string so the output is
1
2
Using .join or [0] returns a nil:NilClass (NoMethodError)

You probably want something like:
macOffice = registeredOffice[/(\d+)\)$/, 1]
scan with capture groups will give you multi-d arrays

The following line:
macOffice = registeredOffice.scan(/\(([^\)]+)\)/).last
returns array since scan returns array of array. For the first line of data.csv, it is ["1"].
I guess you need scalar value for macOffice, thus, you want to use match which only returns non-repetive match using match, which returns array of matches once. For example, you can grab first match from the returned array using [1] subscript, thus:
macOffice = registeredOffice.match(/\(([^\)]+)\)/)[1]
which returns 1.
Assuming you want an array you can write like this:
out = []
CSV.foreach("data.csv") do |line|
registeredOffice = line[0].to_s()
macOffice = registeredOffice.match(/\((\d+)\)/)[1]
out.push(macOffice)
end
puts out.join(",")
to produce 1,2

Related

How to insert integers into an array from same line in ruby?

I am using the following code to insert array value from same line of input
s = Array.new(10)
q = gets
s = q.split(' ')
It is working fine. but if I don't want to take variable to store at first and split after that but directly take input in the array by using following code I fail.
s = Array.new(10)
10.times do
s.push gets.split.map(&:to_i)
end
What is the correct code to take integer inputs from same line? Need help.
You don't have to declare the array first. split method returns an array, and you can assign it to the variable. This will do
s = gets.split(' ').map &:to_i

Ruby JSON parsed output count

I'm trying to parse the output some JSON values in Ruby, but I keep getting an unexpected result.
articlelist = client.get('/v1/my_data/articles')
#debug
puts (articlelist.body)
#Parse the article list and get values
parsed = JSON.parse(articlelist.body)
puts parsed.count
parsed.count do
|currentfile|
inputfile = File.open ('file.example')#file.example should be replaced with local file
filehash = OpenSSL::Digest.new('sha256', 'inputfile')
puts "#{inputfile} has #{filehash.name} hash of #{filehash}"#debug
end
I get the following result:
{"count": 0, "items": []}
2
#<File:0x00000001a83b48> has SHA256 hash of 3de6c8f12dc4c9efe67c0a5bbfe21502cde5ee22e7ef0bc8d348c696db9a4363
#<File:0x00000001a83238> has SHA256 hash of 3de6c8f12dc4c9efe67c0a5bbfe21502cde5ee22e7ef0bc8d348c696db9a4363
If the value of count is zero, why is it giving me a count value of 2 (inputfile is just local example file)?
parsed is an hash with two elements, so parsed.count is 2. parsed['count'], on the other hand, is 0.

Passing original string PLUS matches when using gsub and block?

Rails fans are familiar with params[:terms] or a hash of 'things' passed to the controller collected form the url. E.g.:
params
=> {"term"=>"Warren Buffet",
"controller"=>"search",
"format"=>"json",
"action"=>"index"}
If I want to use "Warren Buffet", "Warren" and "Buffet" in the code below, does anyone know which method I should be using instead? gsub is close, but it takes each match and not the original string too. Unless I'm doing it wrong, which is totally possible:
#potential_investors = []
params[:term].gsub(/(\w{1,})/) do |term|
#potential_investors &lt&lt User.where(:investor => true)
.order('first_name ASC, last_name ASC')
.search_potential_investors(term)
end
Thoughts?
How about:
s = "Filthy Rich"
s.split(" ").push(s)
>> ["Filthy", "Rich", "Filthy Rich"]
Or with scan if you prefer to use the regexp instead:
s.scan(/\w+/).push(s)
>> ["Filthy", "Rich", "Filthy Rich"]
params["term"].gsub(/(\w{1,})/)
returns an enumerator. You could convert it to an array and append the original term to it:
ary = params["term"].gsub(/(\w{1,})/).to_a + [params["term"]]
then process it:
ary.each do |term|
...

A string (thats looks like an array) into an array Ruby

I have an output from an API that look like this... (its a string)
[[2121212,212121,asd],[2323232,23232323,qasdasd]]
Its a string - not an array. I want to convert it to an array and then extract the first two elements in each array in the nested array to:
[2121212,212121],[2323232,23232323]
What's the best way to do this ruby? I could use regexp and extract - but basically the string is already an array, however the class is a string.
I tried
array.push(response)
but that just put the string in to the array as one element. I guess what would be nice is a to_array method
You will need to use regular expression anyway if not eval (shrudder...), this is the shortest one
str = "[[2121212,212121,asd],[2323232,23232323,qasdasd],[2424242,24242424,qasdasd]]"
p str.scan(/(\d+),(\d+)/)
=>[["2121212", "212121"], ["2323232", "23232323"], ["2424242", "24242424"]]
Assuming this is a JSON response (and if so, it is badly malformed and you should talk to the people that are responsible for this) you could write something like:
require 'json'
input= '[[2121212,212121,Asd],[2323232,23232323,qasdasd]]'
input.gsub!(/([A-Za-z ]+)/,'"\1"')
json = JSON.parse input
output = json.map{|x| x[0...2]}
p output
this prints
[[2121212, 212121], [2323232, 23232323]]
Using eval is very bad but I have no other easy option.
test_str = "[[2121212,212121,asd],[2323232,23232323,qasdasd]]"
test_str.gsub!(/([a-z]+)/) do
"'#{$1}'"
end
=> "[[2121212,212121,'asd'],[2323232,23232323,'qasdasd']]"
test_array = eval(test_str)
=> [[2121212, 212121, "asd"], [2323232, 23232323, "qasdasd"]]
test_array.each do |element|
element.delete(element.last)
end
=> [[2121212, 212121], [2323232, 23232323]]

In Ruby irb, can't access a number in a array like fashion

I tried this in irb:
x = 123456
Then I wanted to get a specific position of the number like:
puts x[2]
it returns 0
why is that?
The only (sensible) way to do this is to first convert it to a string then use the [] method:
x_str = x.to_s
puts x_str[0..2] #prints "12"
If you want to retrieve the position of a string within another string, use the index method
puts x_str.index('2') #prints 1
Fixnum does supply a [] method, but it's obviously not what you want.
In your code, it's returning 0 because that is the 3rd (zero-indexed) bit in the binary representation of 123456.

Resources