View on GitHub

Shawn Lindsey

Welcome. I like Ruby/Rails/Javascript.

HOME

< Back To Ruby Test Questions

My Giant List of Answers

Posted on May 9th, 2011.

1. {} Hash.new
2. newhash = { :one => "uno", :two "dos"}
3. newhash[:one] .... you build a hash with {} you call with []
4. nil
5. newhash[:one] = "fixed"
6. They are ordered in 1.9. two hashes with the exact same key and value pairs will eval the same
7. newhash.keys
8. Array ... when you call the above you are returned an array
9. newhash.keys.include?("value")
10. newhash.values
11. newhash.merge!({:newvalue => 7, :another => 8})
12. newhash[:key] = value ... or (worse) newhash.merge!({:newvalue => 7}) ... without ! to not change original
13. yes
14. "He said \"hi\" to me" .. the \ escapes the " ..or use single quote 'He said "hi" to me' .. even better! OR!! %(this is "Quote" here!)
15. Example 'He said "hi" to me' and "I don't do that" ...double quotes to get single quote.. single to get double within
16. \" ... \' ... \n ... \\ .... you escape with the \ (backslash)
17. %(this is the string) the "%" is what creates the string after % can be ( ... ! ... { this is the delimiter
18. newstring = %{It was the best of times
it was the worst of times
}
this is equal to "it was the best of times\nit was the worst of times\n"
19. It is a string literal that preserves whitespace linebreaks and such.
<<delimiter (on its own line)
..
..
delimiter
you have to say newstring = <<delimiter
....
delimiter ..... notice the = up there
20. + ... yes it will leave the original strings in place
21. string1 += string2 ... will add string2 to the end of string1
22. << it will concatinate .. same as += string1 << string2
* 23 The main deal with += is that it re-assigns to the variable. << will modify that variable. if that variable was tied to another re-assign will lose that tie... << will not re-assign
+= will not modify the origional string it RE-ASSIGNS the origional string. << will modify the origional string
x = "one"
x2 = x ... x2 and x will have the same object_id
y = "two"
x2 << y .. this will concat y onto x2 ... and modify x2 in place ... x is tied to x2 so it changes ... when you += it does not modify in place... it re-assigns so the concection is lost
<< for IN-PLACE .... += to re-asssign
24. 1 \t "slash t" is tabbed space
25. Sort of ... this will work '\\\'' ... it will escape the '
26. Use double quotes and #{ } within it ... "xxxx #{var}"
27. substring = string1[3,3] ... or .. substring = string1[3..5]
28. In 1.8 it will return the integer representation. In 1.9 it will return the character ... **** .chr converts an integer to a charactor
29 newstringarray = string1.split ... it returns an array split with no args will split on blank spaces
30. newstringarray = string1.split(/:/) the : is the matching reg expression
31. newstringarray = sting1.split ... newstring = array1.join(" ") ... that will build a string with " " between each element... it will call to_s on each element and create a string with whatever you pass into join inserted between each elelment.. returns a string. You cant call join on a string.. NOT DEFINED!! ha
32. yes ... a == b .... but they are different objects ... == defined for strings this way in the class definition obviously
33. Yes nil is an object
34. true
35. ""
36. "nil"
37. is_a? will verify class of the object. e.g. :test.is_a?(Symbol) ... returns true .. it checks the superclasses too AND MODULES .. a mixed in module will make is_a? evaluate to true
38. Yes. both one and two have the same object_id ...
39. Well.. all method names will become symbols. (maybe something to do with making sure there is only one.... you can define it again / add to it... but there is just one)
40. Well.. all Constants will become symbols
RubyConstant = "Hello there"
41. yes, Ruby turns the quote into a symbol
42. true
43. "Stringthing".to_sym
44. x = :"this has spaces"
45 x = :"This has #{interpolation} in it"
46. The symbol is converted to a string
47. Regexp
48. 1. "this is string"[/is/] or if a variable x[/is/] 2. x =~ /aaba/ ... [/ /] ... this returns a string NOT MATCHDATA ... to get matchdata use .match
49. 1. The matching string is returned.... no match nil is returned .... 2. the position(integer) of the match is returned
50. ? letter before it is optional /ab?/ will return ab or a .... b is fine but optional
+ must match a least one, then unlimited /ab+/ matches ab or abbb... but not a ... must be a b
* matches zero or more. /ab*/ matches a ... ab ... abbbb.... /b*/ matches b...bbb and "" (the match must be at begining.. is this an "anchor typish"? thingy in the Regexp you are doing?)
[] this will match any charactor in there. /[cbr]at/ matches cat, bat, rat, not zat . the [] is within a [] that starts the regexp ... this is a charactor class
| ... or
\d ... backslash d will match any digit
\s ... backslash s will match any whitespace
\w This is a word charactor definded by [/[a-zA-Z0-9_]+/] ( use \w+ to get words ... just w is JUST a word character)
. any character at all except a \n newline
\A matches begining of a string
\Z matches end of a string but wont include newline ... \z includes the newline
^ matches the start of a line (anchor) e.g. /^\d/ finds a number if it starts a line good for matching after \n 's ** note this and the one below also match when the start of a string (or end as below) a newline does not need to be embeded
$ matches the end of a line (anchor) e.g. /\d$/ finds a number if it ends a line good for matching after \n 's
51. The Regexp will match as much as it can .. repitition operators are greedy
52. The first match encountered will be returned
53. That is a / slash...forward slash and a \ backslash ...
54. "this is a number 46"[/[0-9]+/] [0-9] is a range in Regexp
55. "new match 78"[/[^0-9]+/]
56. Capitalize it .. e.g. \W
57. ([a-f].+) as an example this will return all the matches
58. scan will take a regualr expression as an parameter and return an array with all matches
wordarray = "one two-three".scan(\w+)
59. Substites...find and replace .. pass in two parameters find,replace_with
60. find and replace all pass in two parameters find, replace_with g-(global)sub
61. Global methods exist in the program outside of a class defintion. () are optional for params list
sometimes lack of parenthesis leads to ambiguity.
having wrong number of arguaments is not a sytax error. It is a runtime error
global methods e.g. puts are defined on Kernal... Kernal is mixed into all objects and kernal
62. ArgumentError
63. def newmethod(a, b = :default)
64. def varargmethod(*args) if the * sponge operator is in the middle values are assigned left to right then right to left, the * sponges up the others
65. []
66. return :returnvalue, if you do not specify the last statement executed is returned ... once a return is encountered the method passes back control
67. x = method_defined_in_class(3,4) or x = self.method_defined_in_class(3,4) ... the self is implied
68. def private_method(a,b)
a*b
end
private :private_method
you can also define methods underneath the word private in the class
69. You can call the private method within the class, but it will not work if you use self.private_mothod
You will get a NoMethodError
70. CaptialLetter = "value" you can reference it with ::Capitalletter
71. Declare it the same way. You can reference it with ClassName::CapitalLetter or even ::ClassName::CapitalLetter
72. yes
73. yes
74. If you have a nested class that inherets from another class and is also nested in a class the lexical scope would win (nested would take from parent (outside the nest), not from the < inhereted)
the definition of the variable would be searched first locally then searched through the inheritance hiearchy
75. These examples show how ruby does lexical static scoping. static scoping variables are bound locally... dynamicaly scoped variables will pop on and off the stack based on environment
Ruby searches for Constants in this order
1 The enclosing scope
2 Any outer scopes (repeat until top level is reached)
3 Included modules
4 Superclass(es)
5 Object
6 Kernel
76. Every statement will return a value in Ruby
77. if condition == true
:returnval
else
:otherval
end
78. value = if condition == 8
:returnvalue
elsif condition == 9
:othervalue
else
:finalthing
end
You can say this ... assign a value because... EVERY STATEMENT IN RUBY returns a value
If you do this and nothing matches... nil is returned.
79. value = (x == 4 ? "true_value" : "false_value")
80. value = 17 if x == 7
81 unless x == 5
puts "here"
end
82. while x < 5
z + 1
stuff = stuff - 1
end
83. while x < 5 # And yes it stops the whole loop
z + 1
break if interupt_recieved == true
end
84. while x < 5
z + 1
next if interupt_recived == true // next advances tge loop
cc + 1
end
85 for x in arraylist
put x // for is an iterator that will pass in each element of arraylist
end
85b. All of these will pull in the local environment. any changes to vars will be reflected. Scope does not change.

86. false and nil ... note 0 does not evalute to false
87. It will load the file at runtime. require 'filename.rb' ** note it will execute that file... not just load the classes and stuff... it will run it
88. returns an array of all the classes and modules that a given class inherits from
89. Object is at top... of course. Exception inherets from Object ... then StandardError .... RuntimeError
90. begin
do stuff
if bad stuff happens
fail "error in this code block"
end
rescue StandardError => ex
stuff to do after the rescue
ensure
stuff to DEFINATLY DO
end
... um well you can do the statement rescue "stufff to say" ... but yes if you want the structure above it seems you must be in a begin end block...
91. same as raise .. I guess it causes an RuntimeError to be raised always or if in a rescue clause will raise the same exception
92. Yes StandardError is higher up the inheritance hierachy so if it is a RuntimeError of course it is also a StandardError
93. raise
94. Well you could have class MySpecialException < Exception
end
Then you could ... raise MySpecialException "message"
95. assert_equal and assert_raise are methods in... Test::Unit ... Test::Unit provides a rich set of assertions for ruby testing
96. Yes
97. map transforms each element of the array according to what is returned by block. Synonym is "collect"
or better said... map transforms a list by applying a function to each of its elements. map! does this in place
98. When you call an_array.select { |item| (item % 2) == 0 } ... will iterate over the array... passing into the block each item... it will return the items that match the condition in there
99. find_all
100. Find will find the first element that matches a criteria an_array.find { |item| item.size > 4 }
101. Inject takes an inital value as an argument and passes that into the first param of block, second param in block is the collection being passed in to be iterated over
This is basically an accumulator enum.inject(initial) {| memo, obj | block } => obj
The 'memo' is first set by 'initial' from then on out the memo is whatever is returned by the block. this will iterate over each item that is part of the enum... you can use the memo as part of calculations as you go through the list of stuff... you can only call inject on an enum object like an array or a range
*** map and collect will change each value in the array and return an array... inject just returns last thing evaluated.. unless of course you are returning an array or something on purpose
102. Sure you can do this x = (1..3).map { [item] item + 1} this will add 1 to each element of the array... return that array
103. That will open a file and pass each line of the file into a block
104. def new_method
result = yield
result
end

value = new_method { 1 + 2 } ... or you could do a ... do ... end

... or with variables

def new_method(arg1, arg2)
if arg1 == 7
yield "OK","Pass"
else
yield "NO","Fail"
end
end

new_method(7,"TEST") do |ok_var, pass_var |
puts ok_var, pass_var
end
You are executing a method and passing some code in.... the method may be able to use this code... if it wants to execute the code (block) passed in it does so with yield argument, arguments....
105. Yes... you can call yield tons and it will keep executing the block you have passed in
106. if block_given?
107. code_block = lambda do |argument|
x = 4
puts argument
end

code_block.call("called")
YES ... you do NOT need & just define 2 lambdas and then pass them in... the & is to designate the yield
108.another way to write e.g. code_block_name.call(10) is code_block_name[10]
109.you would call the method with .... meth_name(&code_block) ... I think the "&" here kinda splats out the variable into a code block, then the "&" in the method parameter list grabs this code block because it is now in correct block form and not a var referencing a lambda.
110 def method_with_block(&block) .... ** you do not HAVE to pass in a block just because it explicitly takes one
block.call(10)
end
111. 10.times { |index| puts index+1 }

for x in 1..10 do
puts x
end
112. lambda will withing the scope of a function return a value then... if another return is in that function ... it will return that... flow continues... Proc.new will return that value and not another return value in the function ** cant say return in Proc... but it will return a value and then stop the flow **. proc is shorthand for Proc.new... proc does not have to have correct aruments passed in... will be assinged to nil... lambda must have correct argument list
113.

Video = Struct.new(:title, :video_id, :id) do
def to_s
"http://youtube.com/get_video.php?t=#{id}&video_id=#{video_id}&fmt=18"
end

def empty?
@title.nil? and @video_id.nil? and @id.nil?
end
end

then .... new_movie = Video.new("Gone w the Wind", 99, 5.99) to create it
.... note of course that you do not have to have the block here ....you can just have the parameters
114. A Struct is a convienient way to bundle a a number of attributes together using accessor methods without having to write an explicit class
A Struct has the feature that you can get at its elements by index as well as by name:
115. binding method is in module Kernel.. to get a binding call the method binding which is available everywhere as it is in Kernal. A Binding Object encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained.
often you will pass a Binding object into eval to get the context for which eval is being executed .. eval("puts r",the_bind) ... before maybe did ... the_bind = binding somewhere ... or binding is returne somewhere... binding is a function that can be called anywhere returning a binding
116. #
117. =begin =end but there can be no spaces or tabs or anything before these =begin and =end
118. fido.instance_variable_get("@name") this is if you didnt use attr asscr stuff I guess
fido.instance_eval("@name") # string version
fido.instance_eval { @name } # block version
119. Class dog
def set_name
@name = "Fido"
end
def name
@name
end
end
120. you would put after the Class dog .... attr_reader :name
121. you would put after the Class dog ---- attr_accessor :name
122. you define a method initialize(arg1 = :default, arg2 = :default) ... important that the call to obj_name.new("one","two") matches up param wise with the initializer
123 it is returning the object currently defined... not a copy ... a new variable assignment to this returned self will be equal to the orgional object
124 to_s will be called on that ... to_s is defined for all Ruby objects
125 It will return a more complete string version of the object e.g. an Array.to_s will return "123" whereas Array.inspect will return "[1,2,3]" just a bit more complete
126. Of course you can... you open it back up the same way you would define it to begin with
127. You would call this method on the Class Dog.ancestors.include?(ClassName) dog.ancestors returns an array... instance_of? will just tell you what it is an instance of x.instance_of?(Object) will be FALSE .... is different than x.is_a?(Object) which will be TRUE... is_a? will be true for all superclasses and modules
128. Object BasicObject in 1.9
129 0 and 5 ... integers, not float... 6 values possible
130. 'ancestors' is an instance method... you need an object of class Class to use that method... ancestors method is located in class Module class Class < Module .... Module is a Class ... remember a class is a Module really... just a subclass of Module
131. NoMethodError
132. You create subclasses to extend or modify the behavior of a class... you can redefine the methods of the parent class... you can add new methods...etc
133. You call super in the method and this invokes the method in the parent (super) class.
134 No you can only call super from within the overridden method "bark" and that will call on the Super method "bark" you cannot cross over to a new method
135. NoMethodError
136. assert_raise is part of Test::Unit (??) and it takes an argument and a block. It will verify that an Exception was raised in the block that matches the argument passed in
assert_raise(NoMethodError) do
code ...
end
137. You define a module much like a class... module Nameable
module Nameable

def set_name(new_name)
@name = new_name
end

def here
:in_module
end
end
138. No you cannot instantite a module
139. At the top of the class you would do a include Nameable
140. You can call method assert_nothing_raised(Exception) with a block of code passed in. Exception will catch all excepetions thrown
assert_nothing_raised(Exception) do
fido.set_name("Rover")
end
141. Yes you can set instance variables in the module
142. The class definition will override the module definition
143. Yes
144. Use the scope operator :: e.g. fido = Jims::Dog.new
145. No ... in the current scope it would be its own class ... to access the string class it would need to inheret < from ::String
146. the :: is a prefix global scope operator forcing global scope... you now are accessing the global class String
147. class Dog ... remember a class name is just a Constant
148. true
149. MyString now is a constant that references the globalaly scoped ::String... you can now say x = MyString.new("hi")
150. it will return a reference to a constant e.g. Dog.const_get("Name") will get a reference to the Constant Name defined in class Dog. It is defined in Class Module. Class < Module
151. Dog.constants .... I think this is a class class instance method ... it will return an array
152. fido.is_a?(Object)
153. Yes a Class is an object
154. fido = Dog.new
******
def fido.wag
:wag_tail
end
*****
fido.instance_eval {
def wag
:wag_tail
end
}
******
class << jim
def wag
:wag_tail
end
end
******
This is called a singleton method
155. Of course not
156. outside of the class ...
def Dog.make_wag
:wag_tail
end
...... and inside the class
class Dog
def Dog.make_wag
:wag_tail
end
end
.... or inside the class
class Dog
def self.make_wag
:wag_tail
end
end
.... or inside the class
class Dog
def instance_method
:instance_meth_return
end
class << self
def class_method
:a_return
# end
# end
# end
157. Yes
158. No... not really except of course you can define a @@classvariable and this variable is accessible by all instances. shared by the instances
159. It will return the last thing evaluated
160. you get a class object, not an instance object ... this would create 2 ways to instansiate an object e.g. dog = class Dog .... self end *note self at end... this way dog.new and Dog.new both make Dog objects .. silly of course
161. You would call the instance level method ... class ... which returns the class... then you can call the method
x = fido.class.class_level_method ... the .class part returns the class ... now we can call class level methods
162. This is defining a class that inherits from another class... and from that parent class it is inhereting specifically from a nested class in there .... or maybe it is inherting from a module that has this class defined... yes it is last one
163. you can call it with fido.bark ... or fido.send(:bark) or fido.__send__(:bark) .. all objects in Ruby respond to send
164. fido.send("bark" + "_{x}") ... where x is a string that will identify what kind of bark [for instance]
fido.send("BARK".downcase) ... will adjust the message sent to the object
165. fido.__send__(:message) ... because in a project send might get defined... this is a way to ensure you are getting the send you want
166. fido.respond_to?(:message) ... will check if :message is defined
167. class Dog *** Note with send you can pass the message in as a :symbol then the args comma seperated
def bark(*args)
args
end
end
fido = Dog.new
fido.bark("pat","tom","dave")
fido.__send__(:bark, "pat", "tom")
168. method_missing is a method in a class that you can define that will be called anytime an object recieves a message that it doesnt 'understand' i.e. it is undefined in the class
class Dog
def initialize(arg)
@name = arg
end

def method_missing(m, *args, &block)
puts "Could not find #{m}"
end
end
169. When you define method_missing on a class you can pass it any message and it will 'handle' it because it will invoke method missing... but the method really isnt defined so it will [say] false to respond_to? even though it does respond to it
170. Well you can do an if / else where you handle /matches/ on certain messages and if no match you call super(m,*args,&block) and just pass the message up to the 'usual' message handler
You can then also specifically define respond_to? so that it knows what kind of messages the object can handle... calling super on objects it does not respond to
171. a forwarding proxy takes requests from client [processes] and forwards them to the internet. A reverse proxy takes requests from the internet and forwards to internal web servers [Internet ] --> ** [Reverse Proxy]--[Web Server] ** ....vs.... ** [user] -- [forward proxy] ** ----> [Internet]
172. Command , Option, Tab, Shift
173. do end is for multiline ...
174. def bark(arg1-in, arg2-in)
... code ...
yield(x,y) ... this will then execute the code block
end
175. new ... all classes must have a new object and this must be a Class method ... this is how you get an instance
176. and instance of class File represents an open file. class methods can operate on files without opening them
177. class Mylogger
private_class_method :new
@@logger = nil
def create
@@logger = new unless @@logger
@@logger
end
end
178. say you have initialize defined... now you revisit and you want other ways to create objects... you could create a class method that calls new with the new interface
class Shape
def initialize(arg1, arg2)
@sides = arg1
...
end

def Shape.triangle(size) *** or self.triangle(size) this give a new way to initialzie the object
Shape.new(3,size)
end
end
179. the message is of type >obj< and the reciever is also of type >obj< ... so protected methods in the reciever object can be called by the message object....
but to answer the question in general you can get object instance variables with obj.instance_variable_get("@sides")
180. x = obj.clone will produce a shallow copy of the object... variables and such will be copied and the object will have a new object_id ... it is a different object now, ...BUT yes a new object and the instance variables are copied BUT not the objects they reference... so changing the object that is referenced by the instance variable will affect both! You have to do a new assignement on the instance variable to really change that particaluar instances state
181. RUBY_VERSION
182. puts self at the top level will return >> main ... this has a class of Object
183. They are private
184. Yes, true
185. include it... might hae to require a file that contains the module ...require 'name'
186. it is for sending an message to a reciever
187. Yes using a . or a :: works the same for calling a method on an object... I guess the :: just uses the scope of the constant in front of it Shape::add will use the Shape scope and then call the method add ... IF the method name is capitalized(BAD) then :: will first look for a constant in that namespace
188. It writes obj.inspect p()
189. When you define a module it encapsulates all the variables and constants used in that module... you access those variables and constants with the scope :: operator
190. Ruby uses a mixin... which is a module. A module defines 'instance methods'... though you can not get an instance of a module. but these 'instance methods' are 'mixed in' to the class that includes them
191. you say "include Modname" to include / mixin ... require in global scope will make methods available.
192. you must require first if the module is in another file... this drags that file in and include will create a reference to it ... otherwise just use include
193. You need to include the module Comparable then you define the 'comparison operator' <=> with
def <=>(other)
self.duration <=> other.duration
end .... this will give you the < <= == > >= operators with just this. <=> works for integers and floats... otherwise you need to do an if than else for > .. < ... else .. returning -1, 1, or 0
194. the Enumerable module is a mixin that can support things like traversing a collection, sorting, map, include?, find_all. You must define JUST the 'each' method and '<=>'(in Comparable) to get lots of functionality
The main thing about defining "each" is that you need to have a loop where you keep yielding a value... this value is sent to the block where each is called... fido.each { |x| ...code ...} ... silly to have an enumerator for fido but you could and each needs to yield things to that block
def each
@string.scan(/[aeiou]/) do |vowel|
yield vowel
end
end
195.
196. ||=
197. It will first look in the current class, then mixed in modules (last one included looked at first), then superclasses and there mixins
198. You can use load to 'force' a load.. in the case of files changing... require only loads things once
199. the variables and methods that are 'required' or 'loaded' are NOT propageted to the current scope... Global variables ARE propagated....the file will 'execute' and classes can be included... but variables defined there are not in the scope where 'require' or 'load' is called
200. NO include is for modules even though a class is a module
201. it is using the Stuff namespace(a module or a class) and then creating a new T object which is either a class defined in that module or a nested class within Stuff class, :: creates scope
202. Sure... remember the methods in a module will be 'mixed in' to a class, so that could become the way to initialize an object
203. include is for including a module in a class, require and load will drag a file into the current file, load 'forces' a load, require brings it in once. You can not include something unless it is defined in the current file or required
204. No, you cannot do operater overloading... you just have to be able to accept multiple args and then deal with them
205. No... attr_accessor is for instance level vars... you can open up the singleton and define an attr_accessor there though
206. Yes...
207. It will create the whole array... huge... populated with nil and the one value
208. You can use the Marshal module ... x = Marshal::load(Marshal.dump(obj)) ... or you can override the clone method in your class
209. You can't dump objects that have bindings or have procedure or method objects or instances of Class IO or singleton objects... marshalled data loading must match up ruby versions with the data writting
210 a,b = b, a
211. the values on the right are determined in a left to right order then assigned to the left side an array is formed of the rvalues and then the lvalues are populated by each of the rvalues
212. They are the same thing except and, or, not have lower precidence... also it is shortcircuit evaluation... if one of the and expressions is false, it halts evaluation of other stuff... returned is the value of the first expression that halts the comparisions
213. use defined? x it will return nil if undefined or something like "method" or "constant" ** note defined? nil will return "nil" ** ... defined? is an operator! like + - not .... it is not a method
214 =~ !~ ... it returns the start position of the match or nil if no match... match method will return the part of the string that matches ... or array depending on stuff
215. eql? will check that the reciever and the argument have the same type and value 17 != 17.0 because of type eql? and == are usually the same ... usually you override these in classes to get behavior needed.... equal? tests that they have the same object_id
216. $ couple others are $! is the last error message, $& is last reg expression matched $0 name of t ruby script file
217. begin
code...
code ....
rescue SyntaxError, NameError => error_1
puts error_1
rescue ArgumentError => error_2
puts error_2
else
puts "No Errors"
ensure
code ...
code ...
end
218. this is the case subsumption operator... a === b means If a described a set, would b be a member of that set?" ... this is usually defined by the author of the class of 'a' ... case operations use this
219. else is executed if NO Exceptions are raised it is after all resuce's and before ensure
220. begin... end resuce's, else, ensure, retry, raise .... you can say ... bad_non_exitant_method rescue do_this ... do this can be a string that is just returned... it can be a begin end where you have ...code... in between you cant use all the ensure and stuff that you do with a normal rescue clause
221. retry must go in a rescue clause... it will repeate the begin / end block
222. this will allow you to filter the exception... storing the exception in [say] $! or whatever var you want... and it will pass the exception up where it can be better handled
223. it will re-raise the current exception, if there is none it will raise a RuntimeError. This is used in exception handlers resue clauses that need to deal with an exception before passing it on up the stack ... thus the re-raising of same one... it is not competely handled yet
224. it will create a new RuntimeError with it's message as the string
225. it will raise a RuntimeError, with the message, with the stacktrace (minus a couple routines) ... the stacktrace is put in the last ar
226. This is designed to jump out of processing durning normal processing. Ruby will zip through the calling stack to find the matching catch to the throw... An exception is not necissarly raised. This is kinda a exception type construct for normal processing where you have to jump out of a nested constrct.
catch (:done) do
while line = gets
if line == "!"
throw :done
else
puts line + " ** "
end
end
end
227. x == :done ? done_object.new : continue_object.new
228. TONS are ..but... classes Array, File, Integer, Object ..... Modules Comparable, Enumerable, Math, Kernal
229. The end of the line terminates the statement or expression, you can also put in a ; to put multiple statements on one line
230. If the parser can tell that it is an incomplete statement it will continue on next line, e.g. if ends with an operator +,-, etc.. or a comma , ... you can also put a \ backslash in to make it continue on next line
x = 5 + 6 \
+ 10
231. BEGIN {} and END {} are BLOCKS that are executed when a file is loaded and when a program has finished executing END{} ... BEGIN blocks are executed as they are encountered END blocks are executed in reverse order LIFO
232. besides "" or '' you can form strings with a % followed by the literal type then a delimiting character which is non-alphabetic and non-multibyte. if (,{,[,< are used.. the delimter is the closing bracket
%q single quoted string ** note all these 'specialized' %'s have a delemiter after the letter e.g. %q* where * will be the delimeter you don't need a literal after the % ... the literal just makes it more specific... in fact just using % is a great way to make a string with ' and " in it
%Q double quoted string
%w, %W array of strings
%r regular expression
%x Shell command
233. numbers, strings, arrays, hashes, ranges, symbols and regualar expressions
234. Whenever ruby parses <<identifier or <<"quaoted string" it replaces in with a string literal built from succesive logical input lines ... it ends when it encounters identifier ... the ending has to be on its own line unless you put in a <<-EOM (-) before the delimiter
235. Constants ojbect references are all caps with underscore X_DIVISOR = 4.5 class names and modules are CamelCase
236. false is a singleton instance of FalseClass(there can be only one), nil is a singleton instance of NilClass(there can be only one) and the value of uninitalized instance and global variables... to get a singleton instance Ruby must do some stuff? I know you can def self.new in a class and set a class var to false so new instances can not be created... call super if there is no instnaces yet... better yet... require 'singleton' .... include Singleton
require 'singleton'; include Singleton in a class... this makes "new" private
create the (one and only instance) with "instance" method x = Person.instance if you do a y = Person.instance ... both are referenceing the same object ... thats it! just include Singleton then get it with "instance"
237. they are synonyms... yes they are the same
238. __FILE__ , __LINE__
239. only an instance of nil object will respond true to nil?
240. Nope, I guess because you would be re-assigning everytime the method is called... which is counter-intuitive
241. Yup
242. class variables defined at the top level are defined in Object and behave like global variables (put this in your diagram :) )
243. Yes.
244. No
245. Yes, this is part of the blocks binding
246. $& is the string matched following a patter match, this is local to current scope. $$ the process number of program being executed
247. back quotes `backquotes ` or the %x{} ...delimiter
248. Dont think so... you use the scope operator followed by a Constant... you could call a method within that Constant defined namespace and that could return [say] a instnace variable
249. comparison operators are implemented as methods.
250. : and NO YOU DO NOT HAVE to use THEN OR : if the body starts on a new line
251. case starts with case statement then you either have or do not have a target
case case target
when condition when comparison, other_comparison, YET_ANOTHER // comparison === target ... case (with) or (without) target
.... ...
when condition when comparison
... ...
else else
... ...
end end
252. This will be added as a private method in class Object and may be called in any context without an explicit reciever (put this in your diagram)
253. Yes it can
254. Sure you can pass a block to any method... it will only get executed if there is a yield
255. reciever.name[parameters][block] params ... [param,...][,hashlist (=>)][*array][&a_proc] ... pass in params, then a hash, then an array, then a block... couple ways to pass in the block HASH IS BEFORE ARRAY
256. self will be assumed
257. calling super acts just like calling the orgional method except the search for the method body starts in the parent. if no params are passed the orgional method calls paramenters are used
258. (expr1).operator(exrpression2)
259. it is called when you say something like obj.attr = "Hello" .... really obj.attr=("hello")
260. it creates a new name that referes to an existing method, operator, global ref, or reg expression backreferece. it makes a copy so if you redife the method... the alias will still invoke the old method
alias $prematch $` ** NOTE alias does not have to be in a method definition... you can do it anywhere ... cant do to local vars.. only methods global refs, reg expressions
alias plus +
261. No you cant.. you can alias the getter and setter methods if you said something like attr_accessor :name ... you could then alias :fullname= :name=
262. Module#include is a method in Module which is automatically in all Ruby programs. it will add the named modules as anonymous superclasses of the class being defined
263. new is a class method and if you override it you need to call super or else no objects will be created and will return nil
264. It creates kinda makes class method out of an instance method.. but in a module... you can access by scope operator ModuleName::functname or of course you can access within the module ...
265. (a stucture) that remembers the context in which it was defined and uses THAT context whenever it is called... or an anonymous function that preserves the local variable bindings that are in effect when the proc is created
266. {} have higher precedence than do end
267. within the scope of a begin/end block... withing the body of a method (add rescue at end) ...or after a single statement ... statement rescue r_statement
http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ go here and practice with procs, lambdas, methods, and blocks
268. No this is for simple conditional assignments though you can do a begin/end to make more robust... but this is dumb
269. No. the & is really so you can re-use code blocks and pass them in to a method. e.g. you cant pass a block in this way { } and re-use something... you have to write it out... the &proc_name is just so you can pass in something that has already been done.
270. No. the { code block } would want to go into the &name, but so would the other thing you passed in. You would get a 'wrong number of arguments 1 for 0" error
271. Sure. just pass them in like everything else you pass in... no & before it... the & is just for yield .... pass them in then do >> name.call to call the code block you passed in. ... yield will call the &codeblock or the { code block }
272. if it is going to be the code block you have to pass it in with &name and it must be recived as &name or it will not be the "block" ... the first & splats out the lambda into a block
272. no just a block of code will not be considered a "block" of code for that method
273. no. it is just a block of code.
274. It would have to be in a method definitition that had a block passed into it. Proc.new would take the block as its value.... otherwise... for the most part you would never call Proc.new without a block
275. proc
276. You could just call the send method "send".... this sends the object the method and parameters
obj.send(:getinfo,"param1", :param2)
277. The first one is the each/item the second is the count/index
278. eval, class_eval, module_eval, instance_eval ... class eval only works on objects of class Class ... ClassName.class_eval will open the class for defining instance methods .... ClassName.instance_eval would open up the singleton of ClassName ... here any def's would define class methods
279. you just call binding ... no parameters.... returns a binding This method is located in Kernal thus avail everywhere...
280. A binding object encapsulates the execution context
281. You can create a bound Method object or an UnboundMethod object... method objects are bound (have a binding) whereas unbounded dont.. Method objects can get a binding or be unbound.. to execute a method object it needs to be bound.
282. it will disassociate a method from its current reciever.
283. A bound method object is created by calling "method" on a reciever(an instance of a class) with the name of the method as a parameter.... an UnboadMethod is created by calling instance_method on the Class of the object you want to create the unbound method on. e.g. ub = String.instance_method(:length) ... you would then need to bind the method before you can call it ... bind it with an instance of the class
284. Essentially it re-opens a class. You pass it a block or a string(to eval)
285. It will open up an instance of the class, not the class... if you define something you are defining on the singleton...You can pass it a block or a string(to eval)
286. {} have higher precedence. There are no differences except the precedence
287. Reading suggests lambda is favored. proc = Proc.new in Ruby 1.9 and proc = lambda in 1.8 ... in general try to use lambda
288. exec(command <,args>)
289. self.meth_name ... because it is DRY... what if you change the class name? you would have to change all those class methods too
290. inherited is a class method of class Class. classes are instances of Class. inherited is called whenever a subclass of current class is created. You override inherited to [do something] whenever a class is subclassed. def self.inherited(klass_name) .... code .. end
291. loose, strict and numeric coercion. loose is to_i and to_s ...(and more) if an object has any kind of decent representation as a string to_s will convert it. to_str is much more strict, with to_str you only impliment it if EVERYWEHERE you could use a string you can use this object. the method coerce implements Ruby's coercion protocol. coerce guearantees the two objects will have the same class. You must implement coerce.
292. a set of flags, some instance variables, and an associated class.... objects reference classes, and classes reference zero or more superclasses
293. This is used to define a singleton method for the x object. another way to do this is say def x.meth_name ...code ... end .. or even x.instance_eval { .. code w/ def..}
294. The Ruby interpreter will insert an anonymous class inbetween the object and the objects real class. This is the singleton class. this class is searched first for methods on that object.
295. Class. classes are objects themselfs... String is an instance of class Class
296. both of these are defining a singleton method... the singleton on String will be a string class method
297. extend will add the methods in module passed in as parameters to the obj ... if needed it will create the virtual class and add these methods as part of this virtual class. Extend adds the methods... if you call extend in a class it adds those methods to the class as class methods because self is assumed
298. When you include a module Ruby creates an anonymous proxy class that is the direct superclass of the class that does the including.
299. When you include.. the methods in the module are mixed in to the class as instance stuff... when you extend it is same as self.extend which which will create class methods.
300. When the class definition is executed you are creating a Class object named [say] Dog ... the class of self is thus Class while executing the code to create a class
301. when you do self.name you are execting the name method (which is in Module)... Module is a ancestor of Class and thus its instance methods can be called without an explicit reciever within a class definition
302. Yes... one is avail for instance methods the other self.meth_name is inserted into the singleton class.
303. While a class method is executing it can access Class instance methods ie Dog.name because name is defined in Class's superclass .. of course it has access to Object methods and those mixed in with Kernal and stuff
Dog = Class.new { }
304. attr_accessor is an instance method in class Module. when you are defining a class you have an object named ClassName which is an instance of Class... Module is in the chain of superclasses for Class so you can call the instance method attr_accessor when defining a class
305. makes a attr_reader out of the symbol passed in, if you say attr :name, true it makes it an attr_accessor
306. if you [say] @var_name in a class definition that is not in a method definition that @var_name is an instance variable of the class ... not the object... to get an object instance variable you have to define it in something like def initailzie where the object is being created
class Dog

@cls_var = 9 # self here is Dog which is a Class object
def initialize
@inst_var = 9 # self here is a varible that is about to be a Dog object (an instance of a Dog)
end
307. open up class Module and define some methods there. the methods you define there can be called during Dog = Class.new {} or the sytactic sugar class Dog ... end ... attr_accessor is defined there for instance
308. You can't use any of Ruby's keywords as variable names, You could use them as method names though... prob a bad idea though
309. Nope.. a class can inheret from another class but it cant include it
310. Yes... the class methods in the superclass will also be class methods on the child class accessable with the child class name
311. Class... Dog = Class.new or class Dog ..... Dog is now a Class object.. when you say Dog.class_meth ... you are sending a message to the class object (which is Dog) ... class methods are singleton methods on the ClassName
312. You are creating private instance methods of class Object... these are available everywhere; as they are in class object
313. You would just say public :a_method ... this will insert a hidden proxy method in the subclass that invokes the origional methed using super
314. ObjectSpace.each_object { |x| p x} will not return FixNum, Symbol, true, false and nil objects
315. you just call Classname.superclass ... then assign a var to this parent class and call it again... this will build a list of all superclasses... Module::ancestors Module is mixed in so you dont need the scope operator.. so ClassName.ancestors will return all the modules and classes
316. Dog is a object of class Class... Class inherets from Module so all the instance methods of Module are available to the Dog object which is of class Class. One of those methods available to Dog is private_instance_method. false keeps the method from recursing up into superclasses and returning those instance methods
317. BEGIN END __ENCODING__ __END__ __FILE__ __LINE__ alias and begin break case class def defined? do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield
318. First off alias is a keyword and takes two (no comma ,) arguments new_name copy_of_this_name.... alias method is in Module as a Private instance method... takes two arguments( with a comma ,) both make new copies of METHODS!! not vars or stuff like that alias_method :new_name, :copy_of_this_name seems prefered because it can be overridden
319. No. you will not be able to access the value for :one with "one" ... I think rails changes this behavior
320. It is becuase of how the == operator is defined for xx ... which is a String... you could override this ... == is defined differently for Objects ... but String overrides ==
321. overridden == , +, ! ... NOT overridden &&, not, and ... they can be overridden because they are implemented as methods in the class
322. clear method hashname.clear returns {}
323. each { |key, value| } each_key {|key|} each_value {|value|}
324. .... yes code not in def's will be executed as it is encountered during parsing
325. # answer please
326. When you pass in an array to *args that whole array will become the first arg[0] ... if I put the * in front of the array you pass in.. it breaks it up then passes it in which means the broken up array could get sponged up by *args...
def init(*args)
end
init(an_array) init(*an_array)
this will put an_array as [0] element This works... it breaks up the array and passes in each element
(an array within the array)
327. constants, global variables, instance variables and class variables ... methods defined at the top level are available also ...defined in the top level scope in a required file will all be available in the scope of the requiring file
328. -c check for syntax errors (wont run prog) -w allow higher level of warnings -v verbose mode --version show version info -e execute code in quotations
329. value = gets
file = File.new("filename.dat", "w")
file.puts "hey there"
file.close # you can of course have a block here passing in |file| ... this will close it automatically
330. require 'rbconfig' include Config Config::CONFIG["bindir"] This is a hash with keys and values that have all the config info Config::CONFIG.keys returns all the settings
331. It is a collection of files in a directory that is shipped with ruby. you use these with the require command
332. cgi.rb , fileutils.rb, set.rb
333. Library is usually means ruby code that can be loaded or required... extensions are usually thought to be written in C
334. $: this is the set of paths ruby searches when you do a require or load
335. type in irb ... irb --simple-prompt --noecho are common additions ... exit exits irb .... in irb you can do something like ... require 'filenam.rb' ... this will do what you think it does ... then you could use classes and such in there
336. RDoc and ri go hand in hand. Ruby Documentation, Ruby Index...RDoc uses Simplemarkup to format your comments in Ruby code... both are command line tools ... ri String#upcase will display info on the instance method string
337. # is instance methods and :: is class methods
338. rake is a command line tool that reads and executes tasks in a file (Rakefile) .... it is a mini language built in ruby and you just write normal ruby code within it to define tasks. Rake is really an automation tool - its a way of putting all those tasks that you perform in a project into one place
339. loop do loop {
...code... .... code ....
break if x < 8 break if x < 9
end }
340. puts(x = x+1) while x < 10 x+=1 until x ==14
while x > 10 do begin until x > 10 do begin
... .... *until* .... ...
end end while x < 10 end end until x > 10
341. to make a namespace you just [say] namespace :admin do .... end within that you can have more namespace :db do ... end namespace :function do .... end ... within each of these namespaces you define a task :clean do .... end ... you do not have to have tasks in namespaces
namespace :admin do
namespace :db do
task :clean do
....code....
end
task :other do
...code...
end
end
namespace :files do
task :check do
...code...
end
end
end
342 desc "write something here" (this goes right before the task you are defining)
343. rake --tasks
344. RubyGems is a library of utilities that helps with installing Ruby libraries, Ruby applications, and helps package these things. With 1.9 RubyGems is baked in. RubyGems makes sure all dependencies are downloaded and met. The command line tool for this system is 'gem' on unix use sudo gem install because by default local gems are installed into shared directories
345. .gem
346. first it will look first in the current directory then in the local cache maintained by RubyGems system. then it will look at RubyForge.org
347. -l
348. Yes... you can have many returns... e.g. in if than else .... but when a return hits... that is returned and program stops
349. you cannot call the private method with the . operator but send or __send__ will get it done... you can also do e.g. x.instance_eval("private_meth_name")
350. public_send will make sure you are only calling public methods... of course the . dot operator will only allow this also
351. all other args in the definition will try to be filled from left to right and right to left... whatever is left will get sponged up into *arg.. if nothing left [] is that args value... think this is Ruby 1.9
352. No not really...variables hold references to objects .... except for say something like an integer or symbol or true/false/nil... these are not referenced... they are 'immediate values'
353. in a frozen object a 'clone'd' object is also frozen... in a frozen object a "dup" of it is not frozen
354. Dog = Class.new {... } (calling new on Class this is a class method of Class) or fido = Dog.new (calling new on Dog which is an instance of class Class) it is an instance method of class Class... yes there are both... Class.new calls the singleton method and something like [say] Ticket.new will call the instance one ... ie in class Class you have the class method new for something like Dog = Class.new(or the syntactic sugar class Dog ... end) and in class Class you have an instance method new for when you say fido = Dog.new
355. No... caught at runtime
356. -main- top level default object -class object Person- -module object PersonHelper- -an instance of Person- -an individual object executing a singleton method-
357. A "class" method is really just a singleton method on the class object. e.g. class Person ... def Person.some_method ... this is just creating a singleton method on Person....
358. #<Person:0x4402a0> .... and ... Person
359. The variable will win ... you need a . operator to show it is a method self.var_name or you can also use () to establish it is a method
360. when you do 'setter' methods make sure you put the self and . operator... e.g. when calling name= "Shawn" you need to indicate self ... self.name= "Shawn" because ruby will think this is a local variable assignment firstly
361. Global, local, and instance... what about class variables??
362. require english.rb
363. Yes. if you define @@var_name in the parent class... then re-assign it in the child ... it is changed in both!
364. a call to a private method. A private method can only be called by implicit self (no . ) ... the exception is setter methods ... you can use self.age = 7 ... because otherwise if you just use age .. it will think you are defining a local variable
365. They are private methods in class Object .... thus anything decending from Object can call them ... of course because they are private you cannot call with a . operator
366. They can be called from anywhere because they are private methods in Object. Object sits at the top.. it is in the method lookup path of every class (except BasicObject) ... they are private because imagine if they were public... you could then send any object the method name as a message
367. It will print nil ... even though x is never assigned.... ruby parses the code ... and will set aside space for x.... it is never given a value... but it's defalut value is nil ... this is because Ruby needs to know if local variables are local vars or they are method calls
368. case statements use === for the whens... you need to define the === for a class if you want it to work in case statements
369. use begin begin
...code... .... code ....
end until x > 10 end while x < 10
370. An iterator expects a code block... an iterator yields something to code block....an iterator is an object that enables a programmer to traverse a container ....
371. Yes the local variables are available in the block.... if you pass in a var of same name of course that has precedence and is in fact a NEW VARIABLE
372. in the parameter list put a ; followed by the variables you want to be local to this block scope |index,var;local_var1,local_var2| ... now these variables will not effect the ones that are in scope outsie this block
373. No.... the block will pull in the variables in existance but if you make a local variable and assign it in a block it will not be available outside the block
374. Yes, it will just catch any exception and execute what is below it until it encounters an end
375. it is special because the begining of a method or code block serves as an implicit begin/end context ... you dont need to say begin... as long as you want rescue to govern the whole code block
376. YES .. ensure is part of the begin/end structure ... it is run no matter what... you don't need resucues to have an ensure... it is part of the begin end... you can have begin ... ensure ...code... end no resuces
377. "" : [] {} .. ... / / ->() {}
378. x = 1.+(2)
379. %
380. sure... you can make the 'bang' operator do whatever you want ... typically will permanently change the reciever.... by custom only define a method with a ! if there is a similar method without a ! ...note 1.8.7 cannot define ! as a method
381. it is kinda an "un-array" operator... it turns an array into a bare list e.g. names = ["david","john"]; method_name(*names) // this will break out the names into a list to send
382. type error. you must convert the string to a number... ruby will not automatically convert strings to numbers. you can override to_str in Fixnum class to get this to work
383. This requires a string (strictly) so ruby calls to_str .... if it is defined ... it is not here... you will get a "TypeError" .. it will work if you define to_str in Integer
384. local var will produce an error puts x >> error ... puts @x >> nil
385. nil returned asking for an_arry[7] when you defined 3 spots
386. capitalize upcase downcase
rjust(20) ljust(20) center(20,"*")
strip lstrip rstrip
chomp chop clear
replace delete("a") count("a")
crypt succ scan(//)
387. __ENCODING__ USASCII
388. { name: "David", age: 29 } ... 1.9 only I think
389. require 'date' require 'time'
390. x = Date.parse("Jan 2 2009") the parse commmand will make sense of lots of different strings e.g."January 2 2009" is fine... so are lots of others parse returns a Date object
391. They are ordered... the hash remembers what order items were inserted.
392. hash.each_with_index { |(key,value), index| puts "pair #{index} is #{key} >> #{value}"}
393. They are built in methods that take an argument and create a String or Array from that. e.g. x = Array("under the sun") ... it will use the to_ary method to determine how to make it if not avail it will use to-a
394. accesses the array at posiion 3 and returns two things... in an array of course.. you can use this to get, set , whatever

395. add >> a.unshift("dog") remove a.shift..... add >> a.push("dog","cat") remove >> a.pop
396. Hash.new("Default_Value") an argument to Hash.new....this does not make the key/value come into existance ... though you can do this by supplying a block to Hash.new.. if you supply block you can set return value at end and do other stuff before that in the block ..this will execute when a nonexistant key is referenced
397. r = Range.new(1,100,false) false is inclusive .... r = 1..100 .... 2 dots is INCLUSIVE 3 dots EXCLUSIVE
398. include will check if it is IN there... cover will check for < > e.g. r = "a".."z" include?("c") yes ...cover?("abc") yes but "abc" is not included .. cover is for alphebiting checking stuff
399. require 'set' as it is not in Ruby core... a set is a collection... everything in Set is unique... you can merge .... get the union + ... difference - .... intersection & of sets
400. IO objects represent readable and/or writable connections to disk files , keyboards, screens and other devices. An IO object is just like any other object... you send it messages and it returns results
401 STDIN, STDOUT, STDERR ... these are IO objects that can be written to and read from where appororiate
402. $/ ... this is what each responds to for the IO object ... is initally set to "\n"
403. you would redefine the global var $stdout like so ... record = File.open("/tmp/record.txt", w); $stdout = record; .... this will now write all STDOUT to that file... you should not change a constant i.e. STDOUT ... just modify the global var
404. The class of which it is an instance and .. it's singleton class
405. class << obj ... the << obj nototion means 'the anonymous singleton class of obj' ... this prys open the singleton class of obj
406. Metaclasses
407. The singleton methods of a class object are also available to subclasses of that class. B < A A's singleton methods (class methods) are available to B
408. tap will yield the reciever to the code block ... then returns the reciever "hello".tap {|string| puts string.upcase }.reverse HELLO >> "olleH"
409. You alias the old method alias __old_reverse__ reverse ... then you def reverse ... and add what you want to... then within that... call __old_reverse__
410. obj.extend(Module_to_add) .... and you can mix in modules ... or def obj.method .... end
411. pr = Proc.new { puts "Inside a Proc's block"} pr.call
412. proc produces a Proc object .. lambda produces a slightly different varient of Proc object ... both create Proc objects ... lambdas that include a return will not exit surrounding method... lambdas must have correct number of arguments
413. No.. the code block is part of the syntax ...of the method call. blocks are not method arguents either... they are code blocks ad that is a thing unto intself sytactically
414. Yes... this will create a new Proc object ... that you will call with block_var.call
415. when you call the method you put a & in front of the proc (Proc object) this triggers Ruby into knowing your intentions... this will tell the reciever that this is supposed to be the code block.... of course you can't do capture_block(&p) { puts "this is the code block"} .. because &p is indcated as the code block... AND you have supplied a { code block} ... cant do this
416. Yes.. they stay in scope and remain in scope no matter where or when you call it
417. Yes... unlike methods they can be called with wrong number of args... you can use a *an_array to sponge up all arguments too ... a lambda must have the correct number of args
418. 2 things... lambdas must have correct # of arguments...procs do not .... ALSO ...A return statement in a lambda triggers and exit from the body of the lambda... a return in a proc tiggers a return from the method that contains the lambda ... NOTE if a proc has a 'return' in it you MUST be in a method or this will be an error.
419. jim = Person.new; meth = jim.method(:say_hi); meth.call ... this is a bound method
420. meth = Person.instance_method(:talk) you can then bind it to an object of that class though meth.bind(jim) where jim is an instance of person
421. Yes, the initialize of the superclass will get run.. unless you have a initialize in B then that will override
422. it is a number you can set from 0 to 4 to gain protection from dangers like rouge file writting requests.
423. x = Person.new; x.instance_eval("puts @x") ...(or a code block { puts @x} ) this will open up the instance and let you get the instance variables... even if no accessor was defined... you can still get into it
424. they are the same but instnace_exec takes arguments and then a code block... the arguments it takes will be passed to the code block x.instance_exec("s",obj) {|str,obj| self.split(str); puts obj ... etc}
425. puts you inside a class definition body. Person.class_eval do def a_method; puts "hi"; end; end this opens up person... and you still have access to local variables unlike when you use a class Person to open it up... of course if you do a 'def' in here you go out of scope for the local vars though
426. you pass define_method a string or a sybmol and it will define a method in that class.. you also pass it a code block this will be the methods body.... this lets you use local variables that would not be available when using def method_name construct (as this creates new scope)
427. t = Thread.new do \\ you assign t = if you want to be able to wakeup / join / stop / alive? the thread from outside the code block
...code ...
rescue Exception
puts "message"
Thread.exit \\ optional of course .. thread can terminate normally
end
428. The thread will stop when the program terminates... you can call the instance method 'join' on the thread to keep it going...
429. It is like a thread but it does not start until you tell it to with 'resume' .... create with f = Fiber.new do ... code ... end
430. call the class method Fiber.yield .. you can resume with f.resume
431. require 'socket'
s = TCPServer.new(3000)
conn = s.accept
conn.puts `date` \\ backticks `` are for a system command
conn.close
432. Yes... just like all code blocks... the code block gets the current scope and can change the current scope
433. They will output matches based on what thread you are in.
434. these are a storage hash for threads... you can get at the current thread with Thread.current ... Thread.current[:message] = "message here" will store this key/value pair
435. the backticks ... the return value is the output of the program you run...
436. 1. A nonexistent method being called on an object -- ** implement method missing
2. A module being mixed into a class or another module -- ** def self.included(c) for the class or module... this is called automaticly by interpreter when including
3. An object being extended with a module -- ** def self.extended(obj) in the MODULE (you cant extend a class)
4. A class being subclassed (inhereted from) -- ** def self.inherited(subclass) in the class you want to moniter for subclassing
5. A reference being made to a non-existant constant -- ** def self.const_missing(const) within you could use const_set(const,1) to set the constant
6. A instance method being added to a class -- ** def self.method_added(m)
7. A singleton method being added to an object ** def self.singleton_method_added(m)
437. The top level method caller
438. //
439. Both Regualarexpressions and Strings respond to .match
440. match returns an instance of MatchData =~ returnds the index where the match started ... both are equally useful for yes / no answers to if there is a match
441. 1. Literal characters (match this charactor) 2. the dot wildchard character (.) (match any charactor) 3. Character classes (match one of these charactrs)
442. escape it the a backslash \ .. e.g. /a\?/ matches a? .. must escape the ? .... ^ $ ? . / \ [ ] { } ( ) + *
443. \d for any digit ... \w any "word" charactor .... \s ... any whitespace .....
444. when you isolate and save substrings of the string that match particular subpatterns
445. you capture parts of the regexp with ( ) around parts of the regexp. each ( ) will save its matches into $1 .. $2 ...up to n ... where n is the number of ( ) in the regexp match .... these globals only save the last regexp done... to save it you would need to assign the Matchdata object returned to a variable
446. matchdataobject.string returns the origional string matched against ... matchdataobject.captures[1] returns the first capture ...[0] gives the origional string too .. .pre_match gives part of string before match .post_match gives the part after ... .prematch .postmatch .captures
447. Yes, each ( left parenth is how you count the capture e.g. first ( encountered matches [1] ...
448. Quantifiers let you specify HOW MANY times in a row you want to match something
? ... 0 or 1 matches
* ... 0 or more matches
+ ... 1 or more matches
Anchors do not 'consume' charactors they express a constraint: a condition the must be met before the matching of charactors is allowed to proceed
^ ... anchors the beginning of a line
$ ... anchors the end of a line
\A .. anchors the beginning of a string
\z .. anchors the end of a string
\Z .. anchors the end of a string (except for a final newline)
\b .. anchors a word boundary
Modifiers -- a modifier is a letter placed after the final closing forward slash of a regexp literal
//i ... makes the match operations be case insensitive.
//m ... makes the '.' wildcard charactor match ANY charactor including newlines
//x ... makes the regexp ignore whitespace


449. Add a ? after the + or * e.g. abc!def!hij!.match(/.+!/) will match the whole string ... change the reg to /.+?!/ will return to first part of the match. This makes the regex match 0 or 1 or that part... not the whole thing
450. {} braces specify how many repetions in a greedy match. so the phone number reg expression would be /\d{3}-\d{4}/
451. {1,10} will match betwen 1 and 10 ... {3, } will match at least 3
452. A look ahead assertion will verify that the match continues but WILL NOT CONSUME it.... (?= ) ...e.g. /\d+(?=\.)/ will match any number of digits that have a period at the end 456 678. 999 matches 678 but NOT the . and it is not consumed so be carful about how the pattern continues
453. (?<=) ... add the < ... each with its negative are (?=) (?!) and (?<=) (?<!)
454. str = "def"; /abc#{str}/;
455. re = /#{Regexp.escape(str)}/
456. .scan .split .sub .gsub
"This is a string 55 that looks for numbers 88 and returnds them all in an array".scan(/\d/) do |var| ... end will pass each sucessful match into the block
"first=david;last=black;".split(/=|;/) ... will split and return and array splitting on = and ;
"ooooohhhhh".sub(/i/,"a") ... will just replace FIRST match
"oooooohhhh".gsub(/i/,"a") ... will replace ALL GLOBAL sub
457.
458. grep checks an enumerable for matches. you pass in what you want to match against. for an enumerable object grep does a filtering operation on each element based on === ["USA", "UK", "France", "Germany"].grep(/[a-z]/) {|country| country.upcase} ...will match France and Germany and then do a map operation on each match... the block is optional... the block is to map/transform the results array
459.
460. No you cannot override the = e.g. def =(rvalue) ... you can override an assignment though as in def name=(rvalue)
461. from the command line run rdoc filename.rb -r this will parse the file the -r will format for ri ... then you can run ri ClassName and it will give you the Roc about that class.
#:title:ClassName
#Author:: Shawn
#Stuff about the class below // this is the basic format for Rdoc and ri which displays Rdocs
class Classname

end
462. gem server ... then go to localhost:8808
463. a= Hash.new a = Array.new(5) {Array.new(5,"default")}
a[[1,2]]= 23
a[[5,6]]= 42
464. It maintains a database of human readable names and the matching machine readable IP address. It is a hierachy. e.g. your ISP will maintain a table... if it does not have an item in its database it will query higher up server. there are 13 main servers. 10 in USA. Lower level ones get info from the higher ones.
465. Well... this spot is where you would pass the block in if you were going to name it. &block. ... it is also where you can pass in a hash and omit the curly braces.
466. In texmate... open up preferences... advanced and add the path to the ruby you want to use... put it first as I think it looks up PATHS until a success is found... so put it first.. to find out which ruby you are using at terminal say 'which ruby'
467. Yes
468. print "hello"
469. If you include comparable and you need to implement less than and greater than
470. <<END For multiline
I use this
END
%q[When I need " or ' in a string I will use %q or %Q]
"I will use double quotes for string interpolation #{variable} stuff"
'Single quotes for normal stuff'
471. Nothing... there is no block_given ... nothing assigned to &block ... you would only get a problem if you tried to block.call ... cause nothing was passed in
472. Yes. It will return an array made up of the comma sepereated values
473. No you do not need to add the .rb extension (I think)... yes you do need quotes though
474. Arguements variables reference objects, then those objects are passed to the method. You can do what you want with those objects after they are passed. The parameter in the method will name the object while the method is in scope... The variable is translated into an object and the object is then passed
475. Yes, it appears so... I think the parser will see these as local variables and set them to nil... if you use them in the block they will be nil, because nothing was passed in. you cant do this with method calls... you get a wrong number of arguments error
476. Be careful here as I was confused... when you pass in a value to a method e.g.
x = [1,2,3]
def test(x)
...code
x = [99,99,99]
end
test(x)
... you are NOT changing the same x that was passed in... when you exit... x is not changed... you have created a new local variable x in the method and assigned it (naming it x) to the object being passed in... if you want to change x... then do something like x.replace([99,99,99]) mutate it... you are passing an object... the variable is just its name
477. These could be used to group an array. def meth((x,y),z) ... end call with ... meth(array_with_two_elements,8) ... the array is passed intp the () grouping and then broken out into those vars
478. NO... think about all the Wrong number of arguments errors you get.. this is for METHODS.. blocks however or procs do not require the exact right argument list .. will be set to nil ... LAMBDAS and METHODS need the right argument matching
479. array.last array[-1] array.pop will modify array
480. It converts a value into true or false
481. Just handle the exception. it is that simple :)
482. local variables in scope will be available within the while, until and for loops. variables created in these loops are availle outside of the loop as well
483. When you pass a variable into a method you are passing an actual object. The parameter is a local variable to that method... if you change! the value the variable references then it will be reflected after the method ends because this object is mutable and you have just mutated it...if you just assign that paremeter a new value.. that old value (object) still exists and outside of that method there may still be things pointing to it that come back into scope.
484. partition takes a regexp and returns an array with the part [0] before the match, [1] the match, [2] after the match
485. Modifier Meaning
%q[ ] Non-interpolated String (except for \\ \[ and \])
%Q[ ] Interpolated String (default)
%r[ ] Interpolated Regexp (flags can appear after the closing delimiter)
%s[ ] Non-interpolated Symbol
%w[ ] Non-interpolated Array of words, separated by whitespace
%W[ ] Interpolated Array of words, separated by whitespace
%x[ ] Interpolated shell command
486. 5.down_to(1)
487. The for loop is part of the current scope... anything done in the loop is available outside the loop.... the each loop sets up a block
488. freezeing might be an answer... but not as simple as Const = 9 Const.freeze ... this doesnt work... **left as note*** the previous... you dummby of course it doesnt work.. you are RE-ASSIGNING to CONST ... if you try to modify CONST in place it will work because it is frozen, but of course you can just say ='s ... freeze works ... but not if you re-assign
489. Most of Objects instance methods are mixed in by Kernal
490. An enum has state. An Enumerator wraps an interation. Most methods come in 2 forms.. one with a block, and another without a block. A call to an_array.each with a block just passes each element into the block. A call to an_array WITHOUT a block will return an Enumerator which wraps this iteration. A class which allows both internal and external iteration. Most methods have two forms: a block form where the contents are evaluated for each item in the enumeration, and a non-block form which returns a new Enumerator wrapping the iteration.
ary = [1,2,3,4,5] # I think Enumerator is only supported in Ruby 1.9
enum = ary.each # Just made an Enumerator object... this has state, instance variables...etc
enum.next # this will advance through the enum I guess that there is an instance variable that saves the position in the enum
491. True. New local variables created in the block though will be lost
492. defined? is a KEYWORD. defined returns a STRING, or NIL
493. if the first item in the right expression is true it returns that, otherwise it returns the second... if neither was true it would return false. this can be written ... @name ||= ''
494. an_array.find_index("word") ... you can also use block form of course like most stuff
495. p calls obj.inspect and prints ( p foo = puts foo.inspect ) pp does "pretty_inspect"... they are very similiar you have to require 'pp' ... p uses inspect... pp uses pretty_inspect... puts uses to_s ...the pp library adds #pretty_inspect methods to many classes such as String, Array or Struct
496. All variations of {instance|module|class}_{eval|exec} change the current context, i.e. the value for self: obj.instance_{eval|exec} opens the singleton class of obj, while ClassName.{class|module}_{eval|exec} opens the class defintion body itself.
Of course, instance_{eval|exec} are available on any Ruby object (including modules), while {class|module}_* are only available on Module (and thus Classes) module_{eval|exec} is the same as the corresponding class_{eval|exec}
497. It is the same as equal? ... thus it checks that the two objects have the same object_id
498. instance_of? must be an instance of that exact class... kind_of? is true for specified class and all of it's subclasses
499. It is defined for Regex .... === defaults to == .... it is mainly for case statements. location = "area 51" case location; when /area.*/ .... the === definintion in Regex allows this because case operations use === (which ususally default to ==)
500. eql? ... eql? is mainly used for Hash ... otherwise just use ==
501. Well any Numeric classs e.g. Integer... you cant declare a singleton method ... 1.do_this ... also Symbols.. can't declare singleton methods
502. You should create class methods that make the instances instead of complicated parameters supplied to Person.new ...i.e. Person.supervisor Person.cook each create people but the class methods create different versions... supervisor and cook each will call new
503. Child. The class methods of Parent are inherited by Child .. SELF THOUGH IS THE OBJECT TO THE LEFT OF THE METHOD CALL
504. in the module def self.method_name ... you can access this with ModuleName.method_name or ModuleName::method_name .. if you do not do the self it can only be used when mixed into a class because it would have to be instciated.. when you add the 'self' you are making it a module-level method
505. Yes, Like almost everything in Ruby a codeblock will return the last expression that the code block executes.
506. When you have some common functionality where things need to be executed before and after ... and these "before" and "after" evemts never change you can define these events in a method with a `yield` sandwiched between ... you pass in code blocks which have things executed around them
507. if you create say big_array = Array.new(1000000) and in the same scope declare that block that block will keep the array in memory! the block holds onto local variables that were in existance when the block was created
508. if say you have a Document class and instead of reading all the content into a vairable when a Document object is created you save that part of reading the content till you need it. you pass a code block to the initialization and this block gets run when you actually call on the content... by using a code block you also can change how you get the content... maybe read a file... maybe over http...etc
509. You would have to say private_class_method :new .. to get new objects you will need to make a 'create' class method that calls new... make sure there is not a reciver in front of 'new' you can call new from within the 'create' method as 'self' (the class) is assumed as the reciever
510. at_exit takes a block and will execute this when the Ruby program is terminating... at_exit's are executed in a LIFO order
511. This method you supply a block to ... it gets called whenever a method is executed, returned, class opened exectption called or LINE of CODE EXECUTED... everywhere :) e.g. proc_object = proc { |event, file,line,id,binding,klass| puts "#{event} in #{file}/#{line} -- #{id} #{klass}" } ... set_trace_func(proc_obj)
512. You would achive this by creating a module that will be `included` in the class... within that included module you will def self.included(klass) klass.extend(nested_module) end .. within your module you nest a module that will be used to extend the class where this is all getting mixed in.
513. this creates a wrapper around a class... you do a class DocumentWrapper < SimpleDelegator; def initialize (real_doc); super(real_doc);end;end when you create an instance of DocumentWrapper.new(doc) where doc is a Document.new ... the wrapper effectivly implements method missing forwarding all messages to document
514. This is a class that can do lots of file system programming tasks
515. Nothing. They are the same. They check if klass is_a?(klass) is in the inheritance hiearchy ancestors also checks modules mixed in
516. Of course you can always monkeypatch... reopen and redefine. You can also add logic within the class definition to create methods based on certain conditions. ... another example.... def self.enable_encryption( enable); if enabled def encrypt_str; ... end else def encrypt_str; ... end; .. this allows you to (through a class method) change the def of the encrypt instance method
517. 1.9 str[2] 1.8 str[2].chr
518. It must reload the __FILE__ ? it must also remove all the instance methods first with .. instnace_methods(false).each do |method| remove_method(method) end
519. In the class definition you must have within the initialize method ... def initialize ... yield(self) if block_given? ... this will pass the new object into the block for more initialization.... YIELDING SELF AT THE END OF INITIALIZE IS NICE ... YOU CAN NOW SUPPLY A BLOCK TO THE ".new" mehtod
520. You just put the parameters in the block to define_method(method_name) do |var1,var2,var3| ...code .... end these var1's will become the paramters to the new method defined in the class
521. break
522. You can include Singleton ... you can use the Module approach (you can't get lots of BigBoss's ... just this one because it is module not class)
module BigBoss
@index = -1 *** instance variables here are just like class instance variables
@locations = %w{office floor home}
def self.move
@locations[@index = (@index + 1) % @locations.size}]
end
end

Or just create a generic object and add methods to it!
MySingleton = Object.new
MySingleton.instance_eval do
@count = 0
def next
@count += 1
end
end
523. Class definitions, Module definitions, Methods.... ie these three keywords class , module, def ... these change scope ...
524. A top level @instance variable is accessable whenever 'main' takes the role of self. This might be better than a global variable
525. You should never do this. This will catch too much... at WORST case rescue StandardError ... catching Exception will rescue you from things lke Interupt ... cntl-c or SyntaxError
526. New is an instance method of Class ... it is used by [say] Person to create a new person object. Initialize is an instance method of the Person object. Class also has a class method "new" j = Class.new { def meth1 .. end def meth2 ... end } this is an anoymnous class that you could assign to a constant
527. Self ... simply... is the object to the left of the method call. at the top level... self is main... of course... it is -kinda- to the left of the method call

Back To Ruby Test Questions