Code not working after little change [closed] - ruby

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
I'm beginner in programming, I changed my code a little bit so that I can execute some def from the command line. After that change I got an error, but first my code:
require 'faraday'
#conn = Faraday.new 'https://zombost.de:8673/rest', :ssl => {:verify => false}
#uid = '8978'
def certificate
res = conn.get do |request|
request.url "acc/#{#uid}/cere"
end
end
def suchen(input)
#suche = input
#res = #conn.get do |request|
request.url "acc/?search=#{#suche}"
end
end
puts #res.body
Then I wrote into the console:
ruby prog.rb suchen(jumbo)
So, somehow i get the error:
Undefined method body for Nilclass

You're not invoking either of your methods, so #res is never assigned to.
#res evaluates to nil, so you're invoking nil.body.
RE: Your update:
ruby prog.rb suchen(jumbo)
That isn't how you invoke a method. You have to call it from within the source file. All you're doing is passing an argument to your script, which will be a simple string available in the ARGV array.
RE: Your comment:
It should go without saying that the solution is to actually invoke your method.

You can call the methods from the command line. Ruby has a function eval which evaluates a string. You can eval the command line argument strings.
Here's how. Change the line puts #res.body to
str = ARGV[1]
eval(ARGV[0])
puts #res.body
then run your program like so
$ ruby prog.rb suchen\(str\) jumbo

Related

regex to check url format [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 6 years ago.
Improve this question
I want to check if my url format is correct, it has some AWS acces keys etc:
/https://bucket.s3.amazonaws.com/path/file.txt?AWSAccessKeyId=[.+]&Expires=[.+]&Signature=[.+]/.match(url)
^ something like this. Could you please help?
URI RFC specifies this regular expression for parsing URLs and URIs:
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
You can also use the URI module from Ruby standard library:
require 'uri'
if url =~ /^#{URI::regexp(%w(http https))}$/
puts "it's an url alright"
else
puts "that's no url, that's a spaceship"
end
To check for the existence of "some AWS access keys etc" you can do:
require 'uri'
uri = URI.parse(url)
params = URI.decode_www_form(uri.query).to_h
if params.has_key?('AWSAccessKeyId')
unless params['AWSAccessKeyId'] =~ /\A[a-f0-9]{32}\z/
abort 'AWSAccessKeyId not valid'
end
else
abort 'AWSAccessKeyId required'
end
Of course you can just use regular expressions to parse them directly but it gets ugly because the order of the parameters may be different:
>> url = "https://bucket.s3.amazonaws.com/path/file.txt?AWSAccessKeyId=abcd12345&Expires=12345678&Signature=abcd"
>> matchdata = url.match(
/
\A
(?<scheme>http(?:s)?):\/\/
(?<host>[^\/]+)
(?<path>\/.+)\?
(?=.*(?:[\?\&]|\b)AWSAccessKeyId\=(?<aws_access_key_id>[a-f0-9]{1,32}))
(?=.*(?:[\?\&]|\b)Expires=(?<expires>[0-9]+))
/x
)
=> #<MatchData "https://bucket.s3.amazonaws.com/path/file.txt?"
scheme:"https"
host:"bucket.s3.amazonaws.com"
path:"/path/file.txt"
aws_access_key_id:"abcd12345"
expires:"12345678">
>> matchdata[:aws_access_key_id]
# => "abcd12345"
This uses
The positive lookahead of regex : (?=..) to ignore parameter
order
Ruby's regex named captures (?<param_name>.*) to identify
the params from match data
Non capturing groupings (?abcd|efgh)
The matcher (?[\&\?]|\b) to handle Expires=..., ?Expires=... or &Expires=...
And finally the /x free spacing modifier to
allow nicer formatting
We need a url to work with:
url = "/https://bucket.s3.amazonaws.com/path/file.txt?AWSAccessKeyId=somestuff&Expires=somemorestuff&Signature=evenmorestuff"
We also need to escape a bunch of stuff and do some non-greedy matching(.+?):
/https:\/\/bucket.s3.amazonaws.com\/path\/file\.txt\?AWSAccessKeyId=.+?&Expires=.+?&Signature=.+/.match(url)
=> #<MatchData "https://bucket.s3.amazonaws.com/path/file.txt?AWSAccessKeyId=somestuff&Expires=somemorestuff&Signature=evenmorestuff">

Print editable to console in Ruby [duplicate]

This question already has answers here:
What will give me something like ruby readline with a default value?
(6 answers)
Closed 6 years ago.
Let's say I have the following code in Ruby:
print("Enter a filename:")
editableprint("untitled.txt")
filename = gets.chomp!
What would be the function "editableprint" so that "untitled.txt" is part of the input of the user for the gets function? (thus the user can edit the "untitled.txt" string or simply leave it as is")
There are similar questions here and here
However, the solutions there don't seem to work as expected, so it looks this is ruby version or platform dependent?
For example, this does not work for me, but also does not throw an error.
require "readline"
filename = Readline.insert_text("untitled.txt").readline("Enter a filename:")
print filename
But since it looks much better, and should work according to the documentation for ruby >= 2, I am leaving it there for now.
The following works on my system (ruby 2.3.1, OS X)
require "readline"
require 'rb-readline'
module RbReadline
def self.prefill_prompt(str)
#rl_prefill = str
#rl_startup_hook = :rl_prefill_hook
end
def self.rl_prefill_hook
rl_insert_text #rl_prefill if #rl_prefill
#rl_startup_hook = nil
end
end
RbReadline.prefill_prompt("untitled.txt")
str = Readline.readline("Enter a filename:", true)
puts "You entered: #{str}"
I would use vim to edit the file. Vim will save edited files in ~/.viminfo. The last edited file is marked with '0. The pattern of a file entry is 'N N N filename where N stands for a integer.
def editableprint(filename)
system "vi #{filename}"
regex = /(?<='0\s{2}\d\s{2}\d\s{2}).*/
viminfo = File.expand_path("~/.viminfo")
File.read(viminfo).scan(regex).first
end
In order to make this to work you would have to change your code
print("Enter a filename:")
filename = gets.chomp!
filename = "untitled.txt" if filename.emtpy?
edited_filename = editableprint("untitled.txt")

Argument should be a vector [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I'm trying to use the statsample library, but having issues with arrays/vectors.
b = [2,3,4,5,6,7].to_scale
# => #<TypeError: Argument should be a Vector>
Do you know why I might be getting this error?
EDIT 1
Something odd is going on in my environment....
$ irb
irb(main):001:0> require 'statsample'
=> true
irb(main):004:0> b = [2,3,4,5,6,7].to_scale
=> Vector(type:scale, n:6)[2,3,4,5,6,7]
exit
$ bundle exec irb
irb(main):001:0> b = [2,3,4,5,6,7].to_scale
NoMethodError: undefined method `to_scale' for [2, 3, 4, 5, 6, 7]:Array
from (irb):1
from /Users/brandon/.rbenv/versions/1.9.3-p484/bin/irb:12:in `<main>'
irb(main):002:0>
For some reason statsample is not being required when I use bundle exec. I have to manually require 'statsample in my code, even though gem 'statsample is in my Gemfile.
Any thoughts??
I don't see the issue:
irb(main):004:0> require 'statsample'
=> true
irb(main):004:0> b = [2,3,4,5,6,7].to_scale
=> Vector(type:scale, n:6)[2,3,4,5,6,7]
Please make sure that if you use the bundler, put into the Gemfile the following:
gem 'statsample'
And execute the bundle install.
According to the source code:
module Statsample::VectorShorthands
# Creates a new Statsample::Vector object
# Argument should be equal to Vector.new
def to_vector(*args)
Statsample::Vector.new(self,*args)
end
# Creates a new Statsample::Vector object of type :scale
def to_scale(*args)
Statsample::Vector.new(self, :scale, *args)
end
end
class Array
include Statsample::VectorShorthands
end
So here my guess is:
If it's just [Array].to_scale, it should have no problem at all. Unless you pass any argument to to_scale() which is not Vector type, because inside it's calling Statsample::Vector.new(self, :scale, *args), and it's saying "Argument should be equal to Vector.new".

What happens to the object I assign to $stdout in Ruby? [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
EDIT: Don't bother reading this question, I just can't delete it. It's based on broken code and there's (almost) nothing to learn here.
I am redirecting console output in my Ruby program and although it works perfectly there is one thing I'm curious about:
Here's my code
capture = StringIO.new
$stdout = capture
puts "Hello World"
It looks like even though I'm assigning my capture object to $stdout, $stdout contains a new and different object after the assignment, but at least the type is correct.
In other words:
$stdout.to_s # => #<IO:0x2584b30>
capture = StringIO.new
$stdout = capture
$stdout.to_s # => #<StringIO:0x4fda948>
capture.to_s # => #<StringIO:0x4e3b220>
Subsequently $stdout.string contains "Hello World", but capture.string is empty.
Is there something happening behind the scenes or am I missing something here?
EDIT: This might be specific to certain versions only. I'm using Ruby 2.0.0-p247 on Windows 8.1
It works as expected.
>> capture = StringIO.new
=> #<StringIO:0x00000001ea8c00>
>> $stdout = capture
>> $stdout.to_s
>> capture.to_s
Above two line does not print anything because $stdout is now disconnected from terminal.
So I used $stderr.puts in following lines (can also use STDOUT.puts as Stefan commented):
>> $stderr.puts $stdout.to_s
#<StringIO:0x00000001ea8c00>
>> $stderr.puts capture.to_s
#<StringIO:0x00000001ea8c00>
$stdout.to_s, capture.to_s give me same result.
I used ruby 1.9.3. (Same for 2.0.0)
Are you sure there is no other manipulation of $stdout or capturehappening in between?
For me, output looks different. Both capture and $stdout are the same object and subsequently answer to string with the same response (ruby 1.9.2):
require 'stringio'
$stdout.to_s # => #<IO:0x2584b30>
capture = StringIO.new
$stdout = capture
puts $stdout.to_s # => #<StringIO:0x89a38c0>
puts capture.to_s # => #<StringIO:0x89a38c0>
puts "redirected"
$stderr.puts $stdout.string # => '#<StringIO:0x89a38c0>\n#<StringIO:0x89a38c0>\nredirected'
$stderr.puts capture.string # => '#<StringIO:0x89a38c0>\n#<StringIO:0x89a38c0>\nredirected'
Although this question was the result of overlooking a change to the value of $stdout, Ruby does have the ability to override assignment to global vars in this way, at least in the C api, using hooked variables.
$stdout actually does make use of this to check whether the new value is appropriate (it checks whether the new value responds to write) and raises an exception if it doesn’t.
If you really wanted (you don’t) you could create an extension that defines a global variable that automatically stores a different object than the value assigned, perhaps by called dup on it and using that instead:
#include "ruby.h"
VALUE foo;
static void foo_setter(VALUE val, ID id, VALUE *var){
VALUE dup_val = rb_funcall(val, rb_intern("dup"), 0);
*var = dup_val;
}
void Init_hooked() {
rb_define_hooked_variable("$foo", &foo, 0, foo_setter);
}
You could then use it like:
2.0.0-p247 :001 > require './ext/hooked'
=> true
2.0.0-p247 :002 > s = Object.new
=> #<Object:0x00000100b20560>
2.0.0-p247 :003 > $foo = s
=> #<Object:0x00000100b20560>
2.0.0-p247 :004 > s.to_s
=> "#<Object:0x00000100b20560>"
2.0.0-p247 :005 > $foo.to_s
=> "#<Object:0x00000100b3bea0>"
2.0.0-p247 :006 > s == $foo
=> false
Of course this is very similar to simply creating a setter method in a class that dups the vale and stores that, which you can do in plain Ruby:
def foo=(new_foo)
#foo = new_foo.dup
end
Since using global variables is generally bad design, it seems reasonable that this isn’t possible in Ruby for globals.

How to add additional parameters to url? - encode url [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to add additional parameters to url from a hash? For example:
parameters = Hash.new
parameters["special"] = '25235'
parameters["code"] = 62346234
http: //127.0.0.1:8000/api/book_category/? %s parameters
require 'httparty'
require 'json'
response = HTTParty.get("http://127.0.0.1:8000/api/book_category/?")
json = JSON.parse(response.body)
puts json
The following should give you a valid URI which you can use for the json query.
require 'httparty'
parameters = {'special' => '512351235','code' => 6126236}
uri = URI.parse('http://127.0.0.1:8000/api/book_category/').tap do |uri|
uri.query = URI.encode_www_form parameters
end
uri.to_s
#=> "http://127.0.0.1:8000/api/book_category/?special=512351235&code=6126236"
The Tin Mans comment on your question is probably the better answer:
require 'httparty'
parameters = {'special' => '512351235','code' => 6126236}
response = HTTParty.get('http://127.0.0.1:8000/api/book_category/', :query => parameters)
json = JSON.parse(response.body)
puts json
The Addressable::URI class is an excellent replacement for the URI module in the standard library, and provides for just such manipulation of URI strings without having to build and escape the query string by hand.
This code demonstrates
require 'addressable/uri'
include Addressable
uri = URI.parse('http://127.0.0.1:8000/api/book_category/')
parametrs = {}
parametrs["special"] = '25235'
parametrs["code"] = 62346234
uri.query_values = parametrs
puts uri
output
http://127.0.0.1:8000/api/book_category/?code=62346234&special=25235

Resources