What's the variable scope within `class_eval` string?

I am using class_eval to write code to be executed under the context of current class. In the following code, I want to add a counter for changes of attribute values. class Class def attr_count(attr_name) attr_name = attr_name.to_s attr_reader attr_name # create the attribute's getter class_eval %Q{ @count = 0 def #{attr_name}= (attr_name) @attr_name = attr_name @count += 1 end def #{attr_name} @attr_name end } end endclass Foo attr_count :barendf = Foo.newf.bar = 1My understanding of class_eval is that it eval...

Troubles mixing in the #Array and #Enumerable class to my custom class

I am trying to mixin the #Array and #Enumerable classes into my custom class so that I can use the push, pop, size and inject methods (and maybe some other ones). I tried to use include Array as well as class RPNCalculator < Array which I thought was the proper syntax, but got the error:home/action/12_rpn_calculator.rb:2:in `include': wrong argument type Class (expected Module) (TypeError)So I tried using module Array and it seems to be running but not grabbing the methods. So I am really confused. Here is my code:class RPNCalculator include Array attr_accessor :calc...

How to colorize one attribute in ruby hash

I need to colorize only one value in hash, like thatrequire 'colorize'h = {a: 'a', b: 'b'.colorize(:red), c: 'c'}h[:b] returns this"\e[0;31;49mb\e[0m"therefore puts h[:b] works as expected, whereas h.to_s or h.inspect gives this"{:a=>\"\\e[0;31;49ma\\e[0m\", :b=>\"\\e[0;34;49mb\\e[0m\"}"As you can see all the control sequences has been escaped.As the h is being implicitly transformed into string while using puts h, all I get in terminal is this:{:a=>"a", :b=>"\e[0;31;49mb\e[0m", :c=>"c"}without any colours.What should I do to get correct colorized output? ...

Ruby Generate Self-Signed Certificate

I'm trying to generate a self-signed certificate in ruby, but am running into trouble. This is what I currently have right now:require 'openssl'if ARGV.length != 3 then puts "USAGE: #{__FILE__} <type[der|pem]> <private-out> <public-out>" exitendtype = ARGV[0].downcaseprivateKeyFile = ARGV[1]publicKeyFile = ARGV[2]values = [{ 'C' => 'US'}, {'ST' => 'SomeState'}, { 'L' => 'SomeCity'}, { 'O' => 'Organization'}, {'OU' => 'Organizational Unit'}, {'CN' => "somesite.com"}]name = values.collect{...

Using an object oriented approach in Ruby

I have two classes, Class A and Class B.I've recently noticed that they share a lot of the same code. For example:def viewable_by?(user) super || clinic.has_staff_member?(user) || user.system_admin? || self.person == user.personendI want to minimize the code duplicated between the classes. But in refactoring, I've found that much of it doesn't fit neatly into one class that falls cleanly in the Single Responsibility Principle. I want to put it all into a single module, but the methods will have to do with time formatting, viewing permissions, and a few other things.As I se...

Are these objects? Why do they look like that when I print them?

this is my first post and I'm quite new to programming/this site, so I apologise in advance if I'm doing something wrong/annoying. I wanted to find a way to define objects without having to do so for each object. I came up with this class Number def initialize(name) @name = name end def description puts "I'm #{@name} " endenda = ["zero", "one","two", "three", "four"]for i in (0..5) do a[i] = Number.new(a[i])enda[3].descriptionI'm hoping someone can tell me what kind of Frankensteins monster I've created?It seems to work, a[3].description returns "I'm three" but ...

Querying DynamoDB table by hash and range key

I want to query DynamoDB table by hash and range key, using AWS SDK for Ruby V2. Following code can work.dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')dynamodb.query( table_name: TABLE_NAME, key_conditions: { HASH_KEY_NAME => { attribute_value_list: ['hoge'], comparison_operator: 'EQ' }, RANGE_KEY_NAME => { attribute_value_list: ['foo'], comparison_operator: 'EQ' } })But, I want to set multiple items to range key condition.Like this:dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')dynamodb.query( table_name: TABLE...

Module Mixin Instance Tracker

I have the following piece of code, which tracks how many instances there are of a class:module InstanceTracker def self.instances counter = 0 ObjectSpace.each_object do |i| if i.class == self counter += 1 end end return counter endendWhat I want the end user to be able to do is:class Foo include InstanceTrackerendBut when I do that, I get a NoMethodError for Foo.instances. It works fine if I make InstanceTracker a class and do this:class Foo < InstanceTracker; endHow can I make it a module mixin? I played a little with your code. Appar...

Is there a way to access the last match information while iterating with `String#split`?

I want to iterate over a string with a regex pattern. I need to iterate over the matches as well as the non-matches in between them, and access the match information while iteration.If I do not need to access the non-matches, then I can do it with String#scan:"some string".scan(/(some pattern)|(another pattern)/) do if $1 then ... elsif $2 then ... endendBut I need to iterate over the non-matching parts as well, so I probably need to use String#split. But String#split does not take a block, and if I use each after it like:"some string".split(/((some pattern)|(another pat...

Why does a Ruby toplevel assignment method fail to assign instance variables in the REPL?

Setter Works Inside a Class; Fails in REPL Top-LevelIn a related question, I was trying to understand why an assignment method was returning an unexpected value, and learned that this is a surprising but documented edge case in Ruby. However, when I was attempting to debug the problem, I went further down the rabbit hole and ran into some additional surprises that I can't explain.Setter Inside a ClassWhen I have a setter method inside a class such as:class Setter def foo=(bar) @foo = Integer(bar).succ endendthen I get the documented oddness with return values from the ...

Why I cannot mixin an assignment method from a module

Suppose I have a module like this:module MyAssigments def dummy_assignment=(value) puts "it's not assigned #{value}" endendand a class that includes it like this:class MyClass include MyAssigments def x=(value) dummy_assignment=(value) endendtheno = MyClass.newo.x="anything"does not print anything on screen, why ? Ruby has a syntax/paring quirk here: using an assginemnt method for self has to be explicitly qualified thus: def x=(value) self.dummy_assignment=value endwithout the self. part, it is assumed by ruby to be an assignment to a local variable. ...

Student Marks Hash

I've seen solutions posted in other languages but not Ruby so I'm asking here.I'm trying to create a student marks system using Ruby, this should take the student’s name and two marks from the user for that particular student.I decided to try and store these in a hash so it would end up looking something like: student_marks = { "Steve" => 45, 65, "James" => 20, 75, "Scott" => 30, 90 }My code attempt is as follows: continue = "y" student_grades = Hash.new while continue == "y" puts "Please enter student name" name = gets.cho...

Sinatra - how do I get the server's domain name

I'm trying to get the domain name in my Sinatra app but as a newbie I really am struggling to figure out how to do this, and I know it must be possible!Rack::Request#host_with_port looks promising, but I don't know how to get this from my app - how do I get stuff from Rack in my Ruby code?Or is there another way - I'm thinking I don't really want to do this every time a request happens (although it's not too bad), but I thought it'd be better if I could just do it once when the application loads up.Any hints? simply use request.host inside your code.get "/" do puts req...

How can I use Ruby to check if a domain exists?

Something along the lines of:def domain_exists?(domain) # perform check # return true|falseendputs "valid!" if domain_exists?("example.com") If you want to check whether a domain is registered or not, then you need to perform a Whois query.http://www.ruby-whois.org/ [XXX]require 'socket'def domain_exists?(domain) begin Socket.gethostbyname(domain) rescue SocketError return false end trueend [XXX]With ruby-whois is pretty easy:Install gem and require.a = Whois.whois("google.com")a.available?=> falseThere is also a CLI bundled if you install it via ruby g...

how to create a data bag as part of chef script

I need to create a data bag and then an data bag item USING CHEF RECIPE. I an unable to do so.I have the content also ready which is as follows require 'rubygems'require 'chef/encrypted_data_bag_item'secret = Chef::EncryptedDataBagItem.load_secret('/root/data_bag')data = {"id" => "TEST", "root" => "root", "passwd" => "passwd"}encrypted_data = Chef::EncryptedDataBagItem.encrypt_data_bag_item(data, secret)Now that i have the content , i need to create a data bag and an item , and then append the content in to that item . this is the approach which i tried for creatin...

Understanding 'next' in ruby - comparing solutions

I'm doing an online course: Write a method that takes a string and returns true if the letter "z" appears within three letters after an "a". You may assume that the string contains only lowercase letters.This is the solution given:def nearby_az(string) i = 0 while i < string.length if string[i] != "a" i += 1 next end j = i + 1 while (j < string.length) && (j <= i + 3) if string[j] == "z" return true end j += 1 end i += 1 end return falseendThis solution seems unnecessarily complex to me. Specifically, I...

Page 1 of 209  |  Show More Pages:  Top Prev Next Last