i'm trying to map one value to other, following is my code
what im trying to do is call one api and get that values and pass to another api and map both values in the end, i get the values from both apis but failing to concatenate. how to solve this?
response = conn.get("/api/vhosts")
statistics = JSON.parse(response.body)
statistics.each do |vhosts|
# puts "vhostname: #{vhosts["name"]}"
response1 = conn.get("/api/aliveness-test/#{vhosts["name"]}")
statistics1 = JSON.parse(response1.body)
puts "#{vhosts["name"]} " + statistics1.fetch('status', :unknown)
end
end
Preferably, concatenate string using << is a little more faster and performatic:
puts "#{vhosts["name"]} " << statistics1.fetch('status', :unknown).to_s
The error is telling that you are trying to concatenate a string and a symbol. So, one of the two parts is a symbol, not a string. You have some options.
puts "#{vhosts["name"]} #{statistics1.fetch('status', :unknown)}"
or
puts "#{vhosts["name"]} " + statistics1.fetch('status', :unknown).to_s
Related
How do I store Ruby standard outputs to multiple variables?
For example, if I have:
puts "hello"
puts "thanks"
How do I store "hello" and "thanks" to two different variables like strVar (containing the value "hello") and strVar2 (containing the value "thanks").
In my script, I am calling another Ruby script which will puts multiple strings to standard output. How do I store each string from the standard output individually?
I'm not sure that I understand the question, but there are countless numbers of ways to store / print strings. Its hard to imagine a situation where you would have a value following puts that is not entered manually or set programatically.
You can save input variables with gets or $stdin.gets or as an argument with the ARGV array. For example:
puts "Enter the first string"
var0 = $stdin.gets.chomp
If you already have the values saved
var1 = "hello"
var2 = "thanks"
array = [var1, var2]
hash = {:key1 => var1, :key2 => var2}
puts var1
puts var2
array.each do |str| puts str end
hash.map do |k, v| puts v end
You're basically chaining applications/scripts together. There are multiple ways to do it but the simplest path uses the STDIN/STDOUT pipeline.
A simple example would be using two small scripts. Save this as test.rb:
puts 'foo'
puts 'bar'
and this as test2.rb:
v1 = gets.chomp
v2 = gets.chomp
puts "v1=#{v1} v2=#{v2}"
then, at the command line use:
ruby test.rb | ruby test2.rb
which will output:
v1=foo v2=bar
| is how we chain the output of one script to the input of another and isn't part of Ruby, it's part of the OS.
This works because, by default, puts writes to STDOUT and gets reads from STDIN. | wires them together.
Luas string.format is pretty straight forward, if you know what to format.
However, I stuck at writing a function which takes a wildcard-string to format, and a variable number of arguments to put into that blank string.
Example:
str = " %5s %3s %6s %6s",
val = {"ttyS1", "232", "9600", "230400"}
Formatting that by hand is pretty easy:
string.format( str, val[1], val[2], val[3], val[4] )
Which is the same as:
string.format(" %5s %3s %6s %6s", "ttyS1, "232", "9600","230400")
But what if I wan't to have a fifth or sixth argument?
For example:
string.format(" %1s %2s %3s %4s %5s %6s %7s %", ... )
How can I implement a string.format with an variable number of arguments?
I want to avoid appending the values one by one because of performance issues.
The application runs on embedded MCUs.
Generate arbitrary number of repeats of whatever format you want with string.rep if format is the same for all arguments. Or fill table with all formats and use table.concat. Remember that you don't need to specify index of argument in format if you don't want to reorder them.
If you just need to concatenate strings together separated by space, use more suitable tool: table.concat(table_of_strings, ' ').
You can create a table using varargs:
function foo(fmt, ...)
local t = {...}
return t[6] -- might be nil
end
Ps, don't use # on the table if you expect the argument list might contain nil. Instead use select("#", ...).
I am trying to read each line of an uploaded file in Rails.
file_data = params[:files]
if file_data.respond_to?(:read)
file_data.read.gsub( /\n/, "\r\n" ).split("\r\n").each do |line|
inputUsers.push(line.strip)
end
elsif file_data.respond_to?(:path)
File.read(file_data.path).gsub( /\n/, "\r\n" ).split("\r\n").each do |line|
inputUsers.push(line.strip)
end
If the uploaded file contains a mix of Windows and Unix encodings, presumably being due to copying from multiple places, Rails doesn't properly seperate each line of the file and sometimes returns two lines as one.
The application is hosted on a Linux box. Also, the file is copied from a Google docs spreadsheet column.
Are there any solutions for this problem?
Edit:
Hex code for lines that don't get seperated into new lines look like:
636f 6d0d 0a4e 6968
Here's how I'd go about this. First, to test some code:
SAMPLE_TEXT = [
"now\ris\r\nthe\ntime\n",
"for all good men\n"
]
def read_file(data)
data.each do |li|
[ *li.split(/[\r\n]+/) ].each do |l|
yield l
end
end
end
read_file(SAMPLE_TEXT) do |li|
puts li
end
Which outputs:
now
is
the
time
for all good men
The magic occurs in [ *li.split(/[\r\n]+/) ]. Breaking it down:
li.split(/[\r\n]+/) causes the line to be split on returns, new-lines and combinations of those. If a line has multiples the code will gobble empty lines, so if there's a chance you'll receive those you'll need a little more sophisticated pattern, /[\r\n]{1,2}/ which, though untested, should work.
*li.split(/[\r\n]+/) uses the "splat" operator * which says to explode the following array into its component elements. This is a convenient way to get an array when you're not sure whether you have a single element or an array being passed into a method.
[*li.split(/[\r\n]+/)] takes the components returned and turns them back into a single array.
To modify the method to handle a file instead is easy:
def read_file(fname)
File.foreach(fname) do |li|
[ *li.split(/[\r\n]+/) ].each do |l|
yield l
end
end
end
Call it almost the same way as in the previous example:
read_file('path/to/file') do |li|
puts li
end
The reason you want to use foreach is it'll read line-by-line, which is a lot more memory efficient than slurping a file using read or readlines, either of which read the entire file into memory at once. foreach is extremely fast also, so you don't take a speed-hit when using it. As a result there's little advantage to read-type methods, and good advantages to using foreach.
You are substituting \n with \r\n, which is problematic when parsing Windows files. Now \r\n becomes \r\r\n.
Better is to substitute to the Unix line ending format and then split on \n:
file_data.read.gsub( /\n/, "\r\n" ).split("\r\n").each do |line|
becomes:
file_data.read.gsub( /\r\n/, "\n" ).split("\n").each do |line|
Try the built-in method:
File.readlines('foo').each do |line|
Or:
File.open('foo').read.gsub(/\r\n?/, "\n").each_line do |line|
In my Rails application i have a generic search to display the matching results. What I have done to produce matching results is to replace blank spaces by "%" symbol. Its working perfectly but only if there is a gap between the search term . If I enter a single word it says "no matching string".
class TweetsController<ApplicationController
def index
city = params[:show]
search_term = params[:text]
search_term[" "] = "%"
city_coordinates = Coordinates.where('city=?', city)
#tweets = if (city_coordinates.count == 1 && city_coordinates.first.valid_location?)
Tweets.for_coordinates(city_coordinates.first) & Tweets.where("tweet_text LIKE?" ,"%#{search_term}%").all
else if (Coordinates.count != 1 )
Tweets.for_user_location(city) & Tweets.where("tweet_text LIKE ?" , "%#{search_term}%").all
else
#tweets = Tweets.where("%tweet_text% LIKE ? ", "%#{search_term}%").all
end
end
end
end
I am getting output only if I type two words like "Harbhajan Singh", "VVS Laxman" . If I type a single word its saying no matching strings. Anybody help me with this. I need the output both ways the user enters single word or two words or more .Anybody help me with this.
Probably, you are getting an
IndexError: string not matched
Thats because when there is a single word coming in params[:text], this code
search_term[" "] = "%"
raises the error.
You might want to read the string documentation for more details. It states:
If the regular expression or string is used as the index doesn’t match a position in the string, IndexError is raised.
Hope this helps.
I'm not too great with regular expressions myself, so I usually turn to Rubular. It helps you build and test regular expressions for Ruby.
I receive the following error when I try to run my code:
lua:readFile.lua:7: attempt to call method 'split' (a nil value)
I am teaching myself Lua and doing some exercises. I am trying to parse out the individual values in a text file and then do stuff with them. I can open the file and if I don't try to parse out the values I can print the contents.
I have tried, separately:
dollars, tickets = line:split(" ")
dollars, tickets = line:split("(%w+)", " ")
Along with several other iterations I cannot recall at this point.
Here is my code:
myfile = io.open("C:\\tickets.txt", "r")
if myfile then
print("True") --test print
for line in myfile:lines() do
local dollars, tickets = unpack(line:split(" "))
print(dollars)
end
end
print("Done") --test print
myfile:close()
Here is the content of the tickets.txt file in its entirety:
250 5750
100 28000
50 35750
25 18750
I am obviously missing something in the split method but I do not know enough to know what.
Regards.
If you only want to read numbers from a file and do not want to enforce them to be two on each line, you can use this code:
while true do
local dollars,tickets = myfile:read("*n","*n")
if dollars==nil or tickets==nil then break end
print(dollars)
end
The string library in Lua doesn't include a 'split' function. You will have to implement one yourself (there's examples on the Lua wiki), or use Lua's pattern matching functionality to parse out the pieces. For example, you could do something like this:
local dollars, tickets = line:match("(%d+) (%d+)")