Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Ruby TYS
Index -> Programming, Ruby -> Ruby Tutorials
Goto page Previous  1, 2, 3  Next
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Tue Dec 20, 2005 12:06 am   Post subject: (No subject)

With using "if", "or", "?" or "unless"...

Create a very simple "Stack" class which holds elements internally in an instance variable "@elements" of type Array. The class must only have a working "push" method. It must not include code outside of the definition of the "push" method, including other methods.
Sponsor
Sponsor
Sponsor
sponsor
Cervantes




PostPosted: Wed Dec 21, 2005 9:47 pm   Post subject: (No subject)

code:

class Stack
        def push( *values )
                @elements = [] unless @elments   # unless @elements is not empty
                @elements.push( *values )
        end
end
wtd




PostPosted: Wed Dec 21, 2005 9:55 pm   Post subject: (No subject)

Cervantes wrote:
code:

class Stack
        def push( *values )
                @elements = [] unless @elments   # unless @elements is not empty
                @elements.push( *values )
        end
end


Good. Streamlined.

code:
class Stack
   def push(*values)
      @elements ||= []
      @elements.push(*values)
   end
end
wtd




PostPosted: Sun Dec 25, 2005 3:00 pm   Post subject: (No subject)

Add a reverse! method to the module Enumerable. It should be defined in terms of inject. The method may not contain any code other than a call to inject. You are not allowed to define "helper methods". The assignment operator may not occur in the code.
wtd




PostPosted: Wed Dec 28, 2005 3:03 am   Post subject: (No subject)

A demonstration.

The following, which was the answer to a previous question, may be reduced by an additional line.

code:
class Stack
   def push(*values)
      @elements ||= []
      @elements.push(*values)
   end
end


Can become:

code:
class Stack
   def push(*values)
      (@elements ||= []).push(*values)
   end
end


How is this possible?

It's possible because:

code:
@elements ||= []


Is not simply a statement. It is an expression. An expression which happens to return @elements.

In reality, the code in its original form is probably better, but it's important to realize that the code demonstrated here is possible and Ruby is quite happy to work with it.
Cervantes




PostPosted: Wed Dec 28, 2005 10:35 pm   Post subject: (No subject)

Mm mmm!

It's the same reason you can do things like:
code:

a = b = 5

First, we look at the right side: b = 5. b is set to 5, and (b = 5) returns 5, so a = (b = 5), which is a = 5, so both a and b equal 5.

Hurray! Cool
Cervantes




PostPosted: Fri Jan 13, 2006 5:27 pm   Post subject: (No subject)

The first non-wtd TYS (to the best of my knowledge)!

Given a String object, a:
code:

a = "Hello World"

Call the upcase, index, and sub methods on a, to the same effect as this:
code:

a.upcase
a.index( 'l' )
a.sub( 'o', 'u' )


Do this with one line, and you may use a maximum of two dots (".") or double-colons ("::").

You may print the output of method calls if you like.


edit: wtd has solved the problem, within 6 minutes. Just as "Chuck Norris once ate three 72 oz. steaks in one hour. He spent the first 45 minutes having sex with his waitress.", wtd spent most of this time away from the computer. Perhaps wtd is in fact Chuck Norris. Shockingly, I've just discovered evidence that suggests wtd is actually Chuck Norris, but has changed his name sort of like an anagram.

The TYS is still open to all non-Chuck Norris'.
rdrake




PostPosted: Fri Jan 27, 2006 6:19 pm   Post subject: (No subject)

Cervantes wrote:
The first non-wtd TYS (to the best of my knowledge)!

Given a String object, a:
code:

a = "Hello World"

Call the upcase, index, and sub methods on a, to the same effect as this:
code:

a.upcase
a.index( 'l' )
a.sub( 'o', 'u' )


Do this with one line, and you may use a maximum of two dots (".") or double-colons ("::").

You may print the output of method calls if you like.
Here's the solution:
code:
[[:sub, "o", "u"], :upcase, [:index, "l"]].each do |message| p a.send(*message) end
Sponsor
Sponsor
Sponsor
sponsor
Cervantes




PostPosted: Sat Feb 11, 2006 12:42 pm   Post subject: (No subject)

Good, cartoon_shark!

Next:
We can use attr_reader to, in effect, give read access to instance variables, like this:
code:

class Foo
    attr_reader :bar
    def initialize(bar)
        @bar = bar
    end
end

puts Foo.new(42).bar


However, this only works with instance variables. Trying to use this with a class variable produces a NoMethodError when trying to read the value.
code:

irb(main):001:0> class Foo
irb(main):002:1>   attr_reader :bar
irb(main):003:1>   def Foo.set_bar(value)
irb(main):004:2>     @@bar = value
irb(main):005:2>   end
irb(main):006:1> end
=> nil
irb(main):007:0> Foo.set_bar(42)
=> 42
irb(main):008:0> Foo.bar
NoMethodError: undefined method `bar' for Foo:Class
        from (irb):8
        from :0


Write code that makes the following possible:
code:

class Foo
    class_attr_reader :bar, :baz
    def Foo.set_bar(value)
        @@bar = value
    end
    def Foo.set_baz(value)
        @@baz = value
    end
end

class Bar
    class_attr_reader :foo
    def Bar.set_foo(value)
        @@foo = value
    end
end

Foo.set_bar("Pizza for dinner tonight, wtd.  ;-)")
Foo.set_baz("Onion, red pepper, sausage, diced tomato, and two kinds of cheese.")
Bar.set_foo("And most importantly, green olives!  Mmmm!")

puts Foo.bar
puts Foo.baz
puts Bar.foo

Foo and Bar may contain only the code shown above. (They may not be re-opened.)

Edit: Solved, by wtd. 20 minutes. Beast! Once again, the TYS will remain open for a while.
rdrake




PostPosted: Sun Feb 12, 2006 12:34 am   Post subject: (No subject)

Not an easy one at all. I'll send you the solution when you're on IRC later, mostly likely tomorrow.

Anybody else care to try this one out for themselves?
wtd




PostPosted: Tue Feb 14, 2006 2:54 pm   Post subject: (No subject)

As a follow-up to Cervantes' TYS, create a conditional_attr_writer method such that I can write, for example:

code:
conditional_attr_writer :foo => lambda { |self, new_val| new_val > self.foo }.
                        :bar => lambda { |self, new_val| new_val > 3 }
Cervantes




PostPosted: Tue Feb 14, 2006 8:06 pm   Post subject: (No subject)

Nice one, wtd. Smile

Although, I had to change "self" in the lambda function to "current".

Cervantes' Answer wrote:


class Module
def conditional_attr_writer(hsh)
hsh.each_pair { |hsh_key, hsh_value|
class_eval %Q[
@@#{hsh_key}_condition = hsh_value
def #{hsh_key}=(new_val)
@#{hsh_key} = new_val if @@#{hsh_key}_condition.call(@#{hsh_key}, new_val)
end
]
}
end
end

class Bar
conditional_attr_writer :foo => lambda { |current, new_val| new_val > current },
:bar => lambda { |current, new_val| new_val > 3 }
attr_reader :foo, :bar

def initialize
@foo = 42
@bar = 7
end

end
a = Bar.new
a.foo = 42
p a.foo
a.bar = 6
p a.bar
a.bar = 2
p a.bar



And to cartoon_shark, Good job, once again! Hikaru79, you've got some catching up to do. Wink

Edit: Dammit! It's either white text, or no indented code. Spoiler tags would be great.
Edit^2: Dammit! /me removes a single, useless line of code
wtd




PostPosted: Tue Feb 14, 2006 8:49 pm   Post subject: (No subject)

Excellent
wtd




PostPosted: Sat May 13, 2006 5:49 pm   Post subject: (No subject)

New TYS.

Does Ruby have a case ("switch" in some languages) statement?
Cervantes




PostPosted: Sat May 13, 2006 7:16 pm   Post subject: (No subject)

wtd wrote:
Does Ruby have a case ("switch" in some languages) statement?

No. Trick question: Ruby has a case expression.
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 2 of 3  [ 36 Posts ]
Goto page Previous  1, 2, 3  Next
Jump to:   


Style:  
Search: