Strange ruby behaviour with __FILE__ constant?

Hi I have been testing some very basic things in ruby and discover the following. If i put in a file called xxxx.rb in this path "C:\Documents and Settings\Desktop\xxxx.rb" puts __FILE__ and invoke this ruby file in a command line WITHOUT preceding ruby the output is the following C:/Documents and Settings/Desktop/xxxx.rb but if i invoke the xxxx.rb file with ruby (ruby xxxx.rb) in the command like the output is the following: xxxx.rb Why is that difference?? Thanks PD: I'M ON W

Change Ruby Logger output dynamically

I'd like to change dynamically the output used by the Logger. in the lib: @log =, 10, 1024000) in the main class: mylib_instance.log.set_log(STDOUT) # something like that, but this does not work Mickael.

Building a "Semi-Natural Language" DSL in Ruby

I'm interested in building a DSL in Ruby for use in parsing microblog updates. Specifically, I thought that I could translate text into a Ruby string in the same way as the Rails gem allows "4.days.ago". I already have regex code that will translate the text @USER_A: give X points to @USER_B for accomplishing some task @USER_B: take Y points from @USER_A for not giving me enough points into something like"USER_B").for("accomplishing some task").giver("USER_A") Sco

Is it safe to run a ruby script using sudo?

I am running redmine on Ubuntu, and I am running it using sudo. If I try to run as my redmine user, I get permission errors on the log file. Is this safe? Should I be concerned?

Ruby Why can't we access local variable inside rescue?

Local Variable begin transaction #Code inside transaction object = attributes raise unless! end rescue puts object.error.full_messages # Why can't we use local varible inside rescue ? end Instance Variable begin transaction #Code inside transaction @object = attributes raise unless! end rescue puts @object.error.full_messages # This is working fine. end

Do Ruby's "Open Classes" break encapsulation?

In Ruby, programmers are allowed to change predefined classes. So a really bad programmer could do something like: class String def ==(other) return true end end Obviously, almost no one would be quite this dumb, but the idea that more subtle changes to a predefined class could cause problems in already-working code seems to me to violate the principle of encapsulation. Four questions: First, does this, in fact, violate the OO principle of encapsulation? Second, is there a way,

How to limit variable in ruby?

How can I limit a variable that belongs to new Class < Fixnum, between 0 and 255? Or if I can't create a limit in subclass of Fixnim how to write my own class with limit?

Ruby 1.8.7 to 1.9.1 on OS X 10.6

I am currently learning Ruby using Ruby 1.8.7 (pre-installed on OS X 10.6) but understand the latest version is 1.9.1? Is it a requirement for me to 'upgrade' this to get the most out of the language? What are the differences between 1.8.7 and 1.9.1? If an upgrade is advisable can anyone advise how I should go about upgrading my Ruby?

Set Attribute Dynamically of Ruby Object

How can I set an object attribute dynamically in Ruby e.g. def set_property(obj, prop_name, prop_value) #need to do something like > obj.prop_name = prop_value #we can use eval but I'll prefer a faster/cleaner alternative: eval "obj.#{prop_name} = #{prop_value}" end

Trying to learn / understand Ruby setter and getter methods

I'm just learning to program and have decided to try Ruby. I'm sure this is a stupid question, but the instructor is talking about setter and getter methods, and I'm confused. Here is the example: class Human def noise=(noise) @noise = noise end def noise @noise end end From this, the class is instantiated, and I can puts this out: man = man.noise=("Howdie!") puts man.noise This results in Howdie! Now what confuses me is that the instructor is saying without th

Ruby - Hide "^C" on Interrupt

In Ruby I have the following: # Trap Interrupts trap("INT") do puts "Shutting down..." exit end When I interrupt the program, the following is printed (Mac OSX Lion): ^CShutting down... Is there any way to hide ^C from within Ruby?

Cannot get rawr to build jar from a very simple JRuby script

I'm having problems getting rawr to build a jar file. I'm using JRuby on OS X Lion. Installation: jruby --1.9 -S rawr install In the src directory I create a simple hello_jruby.rb containing: puts "Hello JRuby!" The build_configuration.rb file has the following settings: c.project_name = "hello_jruby" c.executable_type = "console" c.main_ruby_file = "hello_jruby" Generate the jar file: $ jruby --1.9 -S rake rawr:jar mkdir -p package/classes/java javac -target 1.6 -cp lib/java/

Ruby Reconstruct original sentence from smaller phrases?

I have an original sentence sent = "For 15 years photographer Kari Greer has been documenting wildfires and the men and women who battle them." and phrases: phrases = [ "For 15 years", "wildfires and the men and women who battle them", "has been documenting wildfires", "been documenting wildfires and the men and women who battle them", "documenting wildfires and the men and women who battle them", "them", "and the men and women who battle them", "battle them", "wildfires",

What does <<DESC mean in ruby?

I am learning Ruby, and in the book I use, there is an example code like this #... restaurant = = "Mediterrano" restaurant.description = <<DESC One of the best Italian restaurants in the Kings Cross area, Mediterraneo will never leave you disappointed DESC #... Can someone explain to me what <<DESC means in the above example? How does it differ from the common string double quote?

Ruby Calling a rakefile from NAnt

I am dealing with a relatively large project, and up until this point building has been done in a NAnt build script. Recently a small portion of development was done in ruby, and is built using a rake file. I would like to create a NAnt target that will call the rakefile. Current set-up in the NAnt build: (Note that the rakefile is in a different directory from the NAnt script) <property overwrite="false" name="project.rootdirectory" value="${project::get-base-directory()}" /> <prope

Unable to decipher this Ruby line containing map operator

I've just seen this line of Ruby code in ruby-trello: # Returns the member who created the action. one :member_creator, :via => Member, :using => :member_creator_id It seems to relate to a superclass method defined as: def, opts = {}) class_eval do define_method(:"#{name}") do |*args| options = opts.dup klass = options.delete(:via) || Trello.const_get(name.to_s.camelize) ident = options.delete(:using) || :id klass.find(self.send(ident))

Ruby soundcloud oauth2 redirect weirdness

When the redirect happens I also see the *access_token* as a parameter in the anchor. I didn't even ask for an access_token just yet because I don't have the code or I am missing something?**some_code**&signed_up=0#access_token=**some_token**&expires_in=21599&scope=%2A

How do I create a subset of an array based on an array of indexes for that array in Ruby

If I have an array like this: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] and I want to select a subset of that array based on this arbitrary array of indexes: [0,1,4,7,8,13,14,15,18,19] with the result being this subset of the first array: [1,2,5,8,9,14,15,16,19,20] My question is, how do I make a simple function (1 or 2 lines) out of the array of indexes and the starting array to get the subset?

Array element additions in ruby

I have this array: a1 = [1,2,3,4] I want to generate this array from a1: a2 = [3, 5, 7] The formula is [a1[0] + a1[1], a1[1] + a1[2], ...]. What is the Ruby way to do this?

How to test simple ruby method, with timing and config dependencies

I have this method: def self.should_restart? if Konfig.get(:auto_restart_time).present?>=Time.parse(Konfig.get(:auto_restart_time)) && Utils.uptime_in_minutes>780 end end In regular Ruby (not Rails) how would I go about testing this? I could monkeypatch Konfig and Utils to return what I want but that seems soooo ugly.

Automatically run RSPec when plain-old Ruby (not Rails) files change

I am writing a Ruby script designed to run from the command line. The script has a corresponding RSpec file that verifies its functionality. The folder structure is: ./main_script.rb ./spec/main_script_spec.rb Running rspec spec in the top level directory works as expected. Test results from the ./spec/main_script_spec.rb file are shown. I'd like to avoid running this manually every time I change either the main script file or the spec file. All my search results turn up things like guard whi

Ruby resque @queue variable returns nil during the test environment but within development it works

In development: 1.9.3p429 :001 > Auction::RiskProfile.instance_variable_get(:@queue) => :low_priority 1.9.3p429 :002 > Resque.queue_from_class(Auction::RiskProfile) => :low_priority 1.9.3p429 :003 > Resque.enqueue(Auction::RiskProfile) => true But in test environment: Resque => Resque Client connected to redis:// Auction::RiskProfile.instance_variable_get(:@queue) => nil Resque.queue_from_class(Auction::RiskProfile) => false Resque.enqueue(Auction::

iterator (array.each) as return value of method in ruby

I have this class : class MyArray attr_accessor :data def initialize(my_object = nil) @data = Array[*my_object] end def <<(y) @data << y end def each @data.each end end And I am using it like this subject =[2, 5, 3]) d = [] subject.each { |i| d << i } The problem is, that it does not iterate even once through the -subject.each-. What should I do to return the "each" value from array as method return value? How to re

Clicking on a Field with Ruby Mechanize

I am trying to use mechanize to click what appears to be a button, however, when I look at the CSS it seems to be a form field. <input type="submit" name="tbe_cws_submit" value="Search" style=" padding:2px; color:#FFFFFF; border-left: 2px solid #11A9F7; border-bottom:1px solid #333333; border-right:1px solid #333333; border-top:2px solid #11A9F7; font-size: 10px; font-weight: bold; font-family:Verdana;" tabindex="13"> When looking at the page from irb, using mechanize, here is what I se

Ruby Grouping an array by comparing 2 adjacent elements

I have an array of objects and I would like to group them based on the difference between the attributes of 2 adjacent elements. The array is already sorted by that attribute. For instance: Original array: array = [a, b, c, d, e] and a.attribute = 1 b.attribute = 3 c.attribute = 6 d.attribute = 9 e.attribute = 10 If I want to group the elements such that the difference between the attributes of 2 adjacent elements are less or equal than 2, the result should look like so: END RESULT resu

Return empty array (Ruby)

I am trying to create a condition statement in Ruby. If my array of various numbers is empty or nil, it should return an empty array otherwise it should sort the numbers. This is what I have so far. num == nil || num.empty? ? return num : num.sort! ...where num is my array. However I'm getting the following error: syntax error, unexpected tIDENTIFIER, expecting ':' I get this error if num is an array of numbers or nil. I'm not sure why this isn't working. Any thoughts?

Ruby Form data is not stored in DB

My models: class LineItem < ActiveRecord::Base attr_accessible :itemable, :adults, :children belongs_to :itemable, polymorphic: true belongs_to :lead belongs_to :cart end class Lead < ActiveRecord::Base has_many :line_items, dependent: :destroy def add_line_items_from_cart(cart) cart.line_items.each do |item| item.cart_id = nil line_items << item end end end class House < ActiveRecord::Base has_many :line_items, :as => :itemable

Ruby Defining Liquid tag, returning string works but processing to return string doesn't?

I'm new to Liquid, but not to Ruby, and I know that Liquid isn't necessarily Ruby for safety reasons. However, in a Jekyll Blog, I tried to define the following code as a plugin: module Jekyll class Person_Index < Liquid::Tag def initialize(tag_name, text, tokens) super @text = text end def render(context) for person in context.registers[:site].data["people"] if (person.index.to_s() == @text.to_s()) return person.display end

Ruby Logstash S3 Input NoMethodError

I'm new to logstash and having trouble getting the s3 input to work. As you can see below, I keep running into this Error: undefined method common_prefixes for {}:Hash issue, and I have no idea why. I am using the latest Logstash from the website, 1.4.2. I download, untar, run with the config below and get the error listed below. Am I missing a dependency? It looks like Logstash bundles everything I should need, including the aws-sdk. My config looks like this: input { s3 { bucket =

Ruby Unable to install rbenv 2.0.0

I'm trying to install rbenv 2.0.0. So, I type rbenv install 2.0.0 And it displays the following error : ruby-build: definition not found: 2.0.0 See all available versions with `rbenv install --list'. If the version you need is missing, try upgrading ruby-build: cd /home/jay/.rbenv/plugins/ruby-build && git pull So, I navigate to the above location and do git pull to upgrade ruby build. Now when I try rbenv install --list, Available versions: and none are displayed. Does any o

Ruby How can I install pg gem on Debian for use on AWS beanstalk app?

This one has appeared in numerous guises on stackoverflow but I still cannot get it to work, despite multiple searches and attempts. Basically I have done: sudo apt-get install postgresql-client libpq5 libpq-dev sudo gem install pg and I have tried bundle config --with-pg-config=/usr/lib/postgresql94/bin/pg_config sudo gem install pg -- --with-pg-config=/usr/bin/pg_config I still get the error message from the logs which says: Gem::Ext::BuildError: ERROR: Failed to build gem nati

Ruby What is the page variable in Capybara tests?

When using Capybara, what is the difference between calling page.find('#name') and find('#name'). Is it that same thing, as this answer states What's the meaning of page and page.body in Capybara I am just looking for more of an explanation and when I would need to use page outside of asserts.

Ruby on Rails, Deploy via Capistrano setup error

I am setting up Capistrano in a rails project for first time. When I run "cap production deploy:check" it goes OK. But when I run "cap prodution deploy" it gives back the following error... (Backtrace restricted to imported tasks) cap aborted! SSHKit::Runner::ExecuteError: Exception while executing as bundle exit status: 127 bundle stdout: Nothing written bundle stderr: /usr/bin/env: bundle: No such file or directory SSHKit::Command::Failed: bundle exit status: 127 bundle st

Ruby Deleting between tags and using variables in regex in `gsub`

My @outbound_text looks something like this: <CREATE-EVENT>\n\t\t\t\t<COLLECTION>PAM</COLLECTION>\n\t\t\t\t<EVENT-TYPE>survey_answer</EVENT-TYPE>\n\t\t\t\t<JSON-STRING>\n\t\t\t\t\t{\n\t\t\t\t\t question1:done,\n\t\t\t\t\t question2:done,\n\t\t\t\t\t question3:done,\n\t\t\t\t\t question4:done,\n\t\t\t\t\t question5:done,\n\t\t\t\t\t question6:done\n\t\t\t\t\t}\n\t\t\t\t</JSON-STRING>\n\t\t\t</CREATE-EVENT>\n\n\t\t\t\n <EMAIL>\n &l

Create New View for Google Analytics with Ruby

I was wondering how to create a new view for google analytics with ruby using the current 0.8.6 version of the library or otherwise? This would be after I have gotten the appropriate access token. The specific call is here: Any tips would be very much appreciated!

Ruby How to fill in a datetime-local field with capybara?

I am using Cocoon to add records. IDs look like workshop_instance_sessions_attributes_1477654140_start_time . At the moment I am traversing the DOM and grabbing the dynamically generated IDs (this works fine) so I can use them to reference the input to fill in. I have tried many things (many that work in console) and still cannot seem to get the spec to work. Below are a selection of things I've tried (first is the variable which holds the id and @time is basically that increments as a

Ruby Minitest ArgumentError when assert_equal two 2D arrays

I have the following test case: def test_primary_key big = [['foo','bar@','baz'], ['cat','moew@','purr'], ['dog','bark@','woof'], ['mew', 'two@', 'blue']] little = [['foo','bar@','baz'], ['dog','moew@','woof'], ['dog','bark@','woof']] args = { big: big, little: little } differ = # assert_equal [["mew", "two@", "blue"]], differ.diff # ArgumentError: wrong number of arguments (given 2, expected 0) assert (differ.dif

Ruby Thor Script through Symlink want calling directory

I want to get the current calling directory when calling a thor script - the script is processed through a Symlink. So calling say( "\n\t#{ Dir.pwd }\n\t" ) Returns the folder the script is hosted in - rather than the CLI directory I called the script from. any help appreciated

Ruby Method not recognizing boolean value

I have a method which take two arguments. A value (fixnum) and a boolean. However, line 4 isn't returning "C" and is returning "D". It isn't recognizing the boolean value and I am unsure why? def grade(num_books, reads_books) if num_books < 10 return "D" elsif num_books < 10 && reads_books == true return "C" elsif num_books.between?(10, 20) return "C" elsif num_books.between?(10,20) && reads_books == true return "B" elsif num_books > 20 r

How do I use multiple integers in an equation (Ruby)

I coded a conversion tool from binary to integer, but it had a limit on how large the number can be. So, I tried to code a formula for binary. I came up with an equation, so I tried to put it into code. Everything worked, except for applying the equation to each digit. This is the equation I came up with: Let d represent the integer Let z represent any (and every) digit d = z[2^(z-1)] This is what I've coded so far: answer = gets.chomp n = answer.reverse # reverses the answer y1 = answer.

Write Errors to Log File in Ruby

I am trying to capture errors, check for a /tmp directory and then write the error to a logfile in that directory, currently I get: .rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/fileutils.rb:252:in `mkdir': Permission denied @ dir_s_mkdir - /temp Here is my code: require 'logger' require 'tmpdir' temp = Dir.tmpdir() log ="#{temp}/error.log", 'w') log.level = Logger::INFO begin rescue StandardError => e log.error "Error - #{e}" puts "For detailed error messages, see

Ruby respond_to? doesn't check singleton class

I'm trying to define a method on an instance, and then get respond_to? to return true. Why doesn't this work? user = user.define_singleton_method(:email) do "some email" end # This works #=> "some email" # I would have expected this to return true user.respond_to?(:email) #=> false Is there any way I get a method defined on a single instance and have it respond correctly to respond_to? Update: It turned out to be a Ruby on Rails issue. RoR provides a different

Ruby Cannot switch gem versions in an rbenv environment

I have rbenv 1.1.2 installed via Homebrew on my macOS 10.14.4. I am having trouble running gems at a version different from the latest available. For example, I have three versions of the xcodeproj gem installed (1.8.2, 1.8.1, 1.8.0, 1.5.7). If I run xcodeproj --version, I see 1.8.2, as expected. However, if I run xcodeproj _1.5.7_ --version, I also see 1.8.2, while expecting 1.5.7. Note that passing the version does something - if I pass an invalid version (e.g. 1.5.0), I do get the "can't

Ruby Sinatra App get request not connecting to sub directory views

I am building my first Sinatra App and I am having some issues connecting my controller to some of the sub directory views I have in place. It currently can go to review_entries but will not find any of the sub locations under review_entries. get 'review_entries/new' do #redirect_if_not_logged_in erb :'review_entries/new' end Here is the current setup for my directory

Ruby Unable to send Gmail Message with Gmail API

Using the Gmail Service to send an email, but I'm having problem with the email format which needs to be passed to Google::Apis::GmailV1::Message, I'm passing raw parameter to it in the following format email_raw = "From: <#{@google_account}> To: <#{send_to}> Subject: This is the email subject The email body text goes here" # raw is: The entire email message in an RFC 2822 formatted and base64url encoded string. message_to_send = B

  1    2   3   4   5   6  ... 下一页 最后一页 共 423 页