Argument should be a vector [closed] - ruby

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".

Related

Ruby will not return hash from function [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 6 years ago.
Improve this question
I have the following code:
def parse_package_url package, directory
branchget = package.split '#'
branch = branchget.length > 1 ? branchget[1] : false
siteget = branchget[0].split(':')
site = siteget.length > 1 ? siteget[0] : 'gitlab'
repoget = (siteget.length > 1 ? siteget[1] : siteget[0]).split '/'
packagename = repoget[1]
packageuser = repoget[0]
path = "#{directory}/#{packagename}"
{
:branch => branch,
:site => site,
:name => packagename,
:user => packageuser
:path => path,
:repo => repoget.join('/')
}
end
Upon running this code, I get the following errors:
syntax error, unexpected tSYMBEG, expecting '}' (SyntaxError)
:path => path,
^
syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.'
:repo => repoget.join('/')
syntax error, unexpected '}', expecting keyword_end
I cannot spot my syntax mistake in this code, and would appreciate if somebody could point it out.
You're missing the comma after :user => packageuser which is causing a syntax error. With errors like these, years of staring have taught me the issue is often with one line above the line number Ruby gives you.

Automagically adding yard doc skeletons to existing Rails legacy code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I would like be able to insert templated YARD doc style comments into my existing Rails legacy application. At present it has few comments. I would like class headers and method headers that have the params specified (by extraction from the method signatures I presume) and placeholders for return values.
In PHP code I had tools that would examine the code and create the doc header comments inserted into the code in the proper spots. In Ruby with Duck typing etc, I am certain that things like the types of the #params etc, cannot be easily guessed at, and I am ok with that - I expect to review the code files one by one manually after insertion. Would just like to avoid having to insert all the skeleton templates into the code (over 500 files) if possible.
I have searched for a gem, etc. that does this and have come across none so far. Are there any out there?
It seems you will have to write it by yourself, but this is not a big problem havig access to the Ruby's S-expressions, which will parse the source for you. So you can do it like this:
require 'ripper'
def parse_sexp( sexp, stack=[] )
case sexp[0]
when :module
name = sexp[1][1][1]
line_number = sexp[1][1][2][0]
parse_sexp(sexp[2], stack+[sexp[0], sexp[1][1][1]])
puts "#{line_number}: Module: #{name}\n"
when :class
name = sexp[1][1][1]
line_number = sexp[1][1][2][0]
parse_sexp(sexp[3], stack+[sexp[0], sexp[1][1][1]])
puts "#{line_number}: Class: #{stack.last}::#{name}\n"
when :def
name = sexp[1][1]
line_number = sexp[1][2][0]
parse_sexp(sexp[3], stack+[sexp[0], sexp[1][1]])
puts "#{line_number}: Method: #{stack.last}##{name}\n"
else
if sexp.kind_of?(Array)
sexp.each { |s| parse_sexp(s,stack) if s.kind_of?(Array) }
end
end
end
sexp = Ripper.sexp(open 'prog.rb')
parse_sexp(sexp)
Prog.rb was:
$ cat -n prog.rb
1 module M1
2 class C1
3 def m1c1
4 a="test"
5 puts "hello"
6 return a if a.empty?
7 puts "hello2"
8 a
9 end
10 end
11 class C2 < C3
12 def m1c2
13 puts "hello"
14 end
15 end
16 class C3
17 end
18 end
What you'll get is:
#line_number #entity
3: Method: C1#m1c1
2: Class: M1::C1
12: Method: C2#m1c2
11: Class: M1::C2
16: Class: M1::C3
1: Module: M1
So you only need to customize the template, and extract the parameters which are available in the same array:
#irb > pp Ripper.sexp("def method(param1);nil; end")
...[:def,
[:#ident, "method", [1, 4]],
[:paren,
[:params, [[:#ident, "param1", [1, 11]]]...
Little bit harder task is to find out what is returned, but still doable - look for :returns while you have :def last in the stack and add it to the last statement of the method.
And finally put those comments above apropriate lines to the source file.

Lambda returning different values [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 9 years ago.
Improve this question
I'm struggling with the following code:
I want a method to check if a string has content or not.
has_content = -> (a) { a!=nil && a.strip != ''}
c = ' '
has_content.call(c)
=> false
c.has_content
=> true
Why is the response different? Clearly I am lacking some Proc/lambdas knowledge.
I believe there is something missing in that code that is causing such behavior.
has_content is not defined for String, so unless you defined it before, it should raise an error
1.9.3p429 :002 > ''.has_content
NoMethodError: undefined method `has_content' for "":String
from (irb):2
from /Users/weppos/.rvm/rubies/ruby-1.9.3-p429/bin/irb:12:in `<main>'
As a side note, here's an alternative version of your code
has_content = ->(a) { !a.to_s.strip.empty? }
And here's an example
has_content.(nil)
# => false
has_content.('')
# => false
has_content.(' ')
# => false
has_content.('hello')
# => true

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.

Code not working after little change [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
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

Resources