w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » RUBY » Page 1
How can I sort by word frequency and then sort alphabetically within each frequency in Ruby?
Hashes do not necessarily sort in natural order; it is down to the individual data structure. If you want to pretty print a hash, you need to sort the keys, then iterate over that sorted list of keys, outputting the value for each key as you go. There are tricks you can do to do this on a single line, or collect the entries from the hash into a sorted array of arrays, but ultimately they all com

Categories : Ruby

Return from context above
Wouldn't you want to just write a wrapper that does exactly that? Functionally it seems you're just ignoring non-ok? responses: def rr response = yield response.ok? ? response : nil end Maybe I'm missing something here but I don't see why you'd need to force a return in another context, something that's not even possible anyway.

Categories : Ruby

cp: cannot stat ‘path/file’: No such file or directory
The shell provisioner runs the given command on the vagrant box, not on the host system. Since the host directory with the Vagrantfile (and, in this case, your install.sh) is mounted as /vagrant in the vm, changing the command to cp /vagrant/install.sh /home/vagrant should to do trick.

Categories : Ruby

Unable to install logtash contrib plugins?
You shall extract logstash-contrib-1.4.1.tar.gz inside logstash-1.4.1 directory with commands: cd logstash-1.4.1 tar zxvf logstash-contrib-1.4.1.tar.gz --strip 1 Then check lib/logstash/outputs/riemann.rb is under logstash-1.4.1.

Categories : Ruby

in rubymotion how to manually invoke table method
To preselect a cell in a Collection View named myColView, call: indexPath = NSIndexPath.indexPathForItem(1, inSection: 0) myColView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: 0) This method does not cause any selection-related delegate methods to be called.

Categories : Ruby

how to call a method immediately before the start of a test run in minitest
You are limited because of the behavior of the spec DSL. If you want to really control when your setup code is run along with the inherited setup, you should use the test-style setup and super. Class A < Minitest::Spec def setup # do stuff setup_runtime_environment end end Class B < Class A def setup super # do stuff after setup_runtime_environment end end Clas

Categories : Ruby

Ruby: comparison of String with String failed (ArgumentError)
Make sure you return the comparison result from the block you passed to sort!. Currently, you return nil (the return value of the last statement, the puts) and this leads to unpredictable results. Change your code to: books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"] books.sort! { |firstBook, secondBook| boolean_value

Categories : Ruby

Ruby downcase method not working as expected
puts "Enter what you want to search through" text = gets.chomp.downcase puts "Enter word to be redacted" redact = gets.chomp.downcase words = text.split(" ") words.each do |word| if word == redact print "REDACTED " else print word + " " end end try it without the exclamation marks.

Categories : Ruby

How to verify buttons which are like images
If you have multiple element with same IDs. Then you can click or verify element using index. query("ImageView css:'#'btn_addRemove'")[0] Let me know, if you issue get resolved.

Categories : Ruby

can I force ruby not to trim my string?
If you want to stop trimming any whitespace at all, then change inputs << line.strip to inputs << line and all your whitespace will be preserved. If you want to stop trimming whitespace on the left side only, change it to inputs << line.rstrip and it will trim only right-side whitespace.

Categories : Ruby

how to use Sinatra-cache?
You have to disable cache by your self. In your get methods, just add no-cache parameter :cache => false to erb or haml calls. E.g.: # To turn off caching on certain pages: get('/nocahce') { haml(:view_name, :cache => false) # <- here } Take a look on documentation for more details. Have a nice day!

Categories : Ruby

What does Array#reverse method in Ruby do?
> array => [5, 4, 9, 8, 7, 1, 2] > array.sort.reverse # it will sort the array by value in descending order => [9, 8, 7, 5, 4, 2, 1] Note: sort : Returns a new array created by sorting self. reverse : Returns a new array containing self‘s elements in reverse order. See how it works: > array.reverse # it will reverse the array by indexing => [2, 1, 7, 8, 9, 4, 5]

Categories : Ruby

2-Level Ruby Ternary Operator Not Working
It is getting assigned to intel. It is not getting assigned to @intel, which is maybe what you intended? You could change that line to @intel = intel.is_a?(String) ? "string not allowed" : check_range(intel) ? "Invalid Stat for intel" : intel But really your code needs some dramatic refactoring. Why the check for String? Wouldn't other classes also not be valid? Why store error messages in the

Categories : Ruby

How do I fetch column names from a db table into an array, using PostgreSQL and Ruby?
Are you using the pg gem? If so, you can try this: require 'pg' # `db_config` must contain your database configuration conn = PG::Connection.open(db_config) column_names = conn.query("SELECT * FROM my_table LIMIT 1").first.keys

Categories : Ruby

Access machine ID from trigger
As explained in the ticket solution, you can use @machine.id. An example: config.trigger.after :halt do info "Machine ID: #{@machine.id}" end

Categories : Ruby

Need to store time field input as local time
The most direct way to get at the user's locale is in the browser, with JS. new Date(userDateString).getTimeZoneOffset() will return the user's offset in minutes from UTC. You can use that to convert the times to UTC before sending them up to the server. Of course, this won't work if you need to support JS-less users. Those users will need some other approach--you could make a "my time-zone" dropd

Categories : Ruby

What are empty-body methods used for in Ruby?
There may be several reasons. One case is when a class is expected to implement a specific interface (virtually speaking, given that in Ruby there are no interfaces), but in that specific class that method would not make sense. In this case, the method is left for consistency. class Foo def say "foo" end end class Bar def say "bar" end end class Null def say end end In o

Categories : Ruby

What's the common fast way of expressing the infinite enumerator `(1..Inf)` in Ruby?
I would personally create my own Ruby class for this. class NaturalNumbers def self.each i = 0 loop { yield i += 1 } end end NaturalNumbers.each do |i| puts i end

Categories : Ruby

Ruby - kernel_require.rb:54 in 'require': Cannot load such file (from GitHub repository)
I forked this same GitHub project, RubyMan, and cloned it on Ubuntu 14.04 LTS. I installed the current stable release of Ruby 2.2.2. I ran into almost the same problem as above when I changed to the RubyMan folder and ran: ruby Main.rb Here is the stack trace: /usr/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- colorize (LoadError) from /usr/li

Categories : Ruby

How to use classes in Shoes?
I'm not too familiar with Shoes, but the problem you're likely having here is that you're trying to call a method called para on the Post class, and no such method exists. When you call Shoes.app do ..., I suspect Shoes is changing the current execution context to one that includes those methods. That is, you should expect this to work: Shoes.app do para "The author of all posts is Jimmy" end

Categories : Ruby

How to read value in cell from database
Is there a reason you're not using an ORM like ActiveRecord? Although it certainly has some downsides, it may well be helpful for someone who is new to databases and ruby. If you want a tutorial on active record and rails, I highly recommend Michael Hartl's awesome free tutorial[1]. I'm not exactly sure what you're trying to do, but I can correct a couple of misconceptions. First of all, result

Categories : Ruby

How to speed up the process of a simple array iteration?
Profile your code to see what the bottleneck is. If I had to guess, Time.zone.parse is probably where >=80% of the computation is going. Given a fixed date format, you could dramatically improve performance by constructing a date object manually, extracting components from substrings at particular ranges.

Categories : Ruby

Swap adjacent elements in array
Without splitting it into arrays then joining to new arrays (because that doesn't seem necessary): def some_method(string) swapped_strings = [] (0...string.size-1).each do |i| temp_string = string.dup temp_string[i], temp_string[i+1] = temp_string[i+1], temp_string[i] swapped_strings << temp_string end swapped_strings end

Categories : Ruby

Getting output from Ruby Net::SSH sessions
change channel.on_data do |channel, data| data end to channel.on_data do |channel, data| puts data end the data mentioned is the response from the server and add channel.send_channel_request 'shell' do |ch, success| if success puts 'user shell started successfully' else puts 'could not start user shell' end end

Categories : Ruby

rake db:migrate no longer working, no error message
I need to respond to this as an answer as I can't comment yet without enough rep (seems silly as a comment might be better at this point). However the files missing are likely old migration files that would start with the timestamp filename followed by the method. eg. 20140506035953_create_table.rb At some point you must have deleted migration files because you no longer wanted or needed the

Categories : Ruby

encrypt data bag with knife from inside ruby
I worked out how to encrypt inside of ruby, just use this code: require 'chef/knife' #require 'chef/encrypted_data_bag_item' #you need to do this in chef version 12, they've moved it out of knife and into it's own section require 'json' secret = Chef::EncryptedDataBagItem.load_secret Secret_Key_Path to_encrypt = JSON.parse(json_to_encrypt) encrypted_data = Chef::EncryptedDataBagItem.encrypt_da

Categories : Ruby

Execute lambda in the context of another object
The issue here is that the receiver of instance_eval is passed to the block as an argument. Procs allow for undeclared arguments, lambdas do not. pr = proc {|*args| p args; a + 1 } A.new.instance_eval &pr [#<A:0x43668596>] => 6 If you declare your lambda such that it receives an argument, it works just fine: > la = ->(recv) { a + 1 } > A.new.instance_eval &la =>

Categories : Ruby

ConnectionFailure while connecting to mongoDB from external script
SOLVED! I solved this problem using rhc to create a tunnel for communication between my local machine and openshift aplication. All you need to do for opening tunnel you just need to run rhc port-forward APP_NAME and this will bind some ports and starts communication between local machine and the server.

Categories : Ruby

AWS Ruby SDK v2 Stack filtering
It is not possible for the Ruby SDK to request stacks filtered by tags. The Amazon CloudFormation ListStacks API only supports filtering stacks by status. You can view the API for ListStacks here: http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_ListStacks.html

Categories : Ruby

Ruby script to prompt for password and have user enter password again for verification
This is what I have changed: #!/usr/bin/ruby # require 'rubygems' require 'highline/import' def getPassword(prompt) loop do word = ask("#{prompt}") { |x| x.echo = "*" } verify = ask("#{prompt} Again") { |z| z.echo = "*" } if word != verify puts "They do not match" else puts "They Match" return word break end end end user_password = getPas

Categories : Ruby

Writing Arrays using grep
There are several issues with your code: You open "input.txt" with open mode "w+". According to the documentation, this truncates your file to zero length. An empty file doesn't contain any lines and therefore, file.each_line doesn't invoke the block. If you want to read from the file, use "r", which is the default: file = File.open("input.txt") You don't close file. Use the block form which

Categories : Ruby

ruby using if inside loop with user input
try this: while cond == false if (line.numeric? ) puts "Ok nice " cond = true else puts "Please enter number only " line = gets.chomp.strip end end

Categories : Ruby

Delete a string in an array when it exist in another array
Use operator - irb(main):004:0> result - exclude => ["pda600", "xda700", "wdw300", "ztz800", "lkl100"] If you really need to modify your result array you can use reject!. However if it is the case, you better review your code. result.reject! {|s| exclude.include? s}

Categories : Ruby

end to end test of a ruby console app
Inspired by this gem which has a fairly simple implementation, I wrote a method which captures console input & output and can, therefore, be used in tests: require 'stringio' module Kernel def emulate_console(console_input) $stdin = StringIO.new(console_input) out = StringIO.new $stdout = out yield return out ensure $stdout = STDOUT $stdin = STDIN end end

Categories : Ruby

No implicit conversion of HTTParty::Response into String
The error you're getting is a TypeError. It's raised when you pass the wrong kind of argument to certain methods. You can rescue it like this: begin parsed_response = JSON.parse(response) rescue JSON::ParserError, TypeError => e puts e end I wouldn't recommend this, though. The reason you're getting a TypeError is that JSON.parse requires a String object, and you've passed it a HTTParty:

Categories : Ruby

Is JRuby's implementation of Kernel#__method__ broken?
It may be a defect in JRuby's implementation of __method__, or it may be a bug in the implementation of define_method, or it may be strictly limited to the use of the two together. Look what happens if you cast the Proc object into a block by using the & operator: DEFINITION = proc { __method__ } class C define_method :one, &DEFINITION define_method :two, &DEFINITION end o = C.n

Categories : Ruby

valid_json? check in ruby is not working
More specifically than in my comment, I suggest you use something like this: value = nil begin value = JSON.parse(response) # do whatever you do when not error rescue JSON::ParserError, TypeError => e puts "Not a string, or not a valid JSON" # do whatever you do when error end

Categories : Ruby

Why doesn't this comparison approach work in Ruby
Because that's not how it works. The definition of A || B is A if A is truthy, B otherwise. The evaluation order is as in mathematics, parentheses go first; so ('R' || 'P' || 'S') is 'R' (because at least the first of them is truthy; in fact all of them are). Then 'P' == 'R' is obviously false. You need to write it as: s[1] == 'R' || s[1] == 'P' || s[1] == 'S' Shorter alternative: %w(R P S).i

Categories : Ruby

Recursive call with private method in Ruby
You have two private_method methods, one in the superclass (that is private) and an overriden one in the subclass (that is public). Your code works because the self.private_method in the superclass isn't calling its own private private_method, but the one that is public in the subclass. This, for example, will not work: Methods.new.send(:private_method)

Categories : Ruby




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.