- Symbols begins with :
- function call do not need (), just mention it.
- If you want to get the function object instead of the result of calling it, use method(:function_name), obj.method(:method_name) or class.instance_method(:method_name).
- no curly braces, use `end` key word.
- string enclosed by "" can be perform fancy variable substitute; with '', no substitute.
- substitute: #{variable_name}, #{variable_name.method}
- Inside class, @prop means `this.prop`
- To define class properties: attr_accessor, attr_reader, atter_writer
- Result of the last express in a method definition will be the return value.
- Can define constants by using upper case letter as variable name. It is still mutable, but the interpreter will complain.
- By convention, methods end with ? are predicates, they all return a boolean value.
- By convention, methods end with ! would perform some mutation to the object.
- list.sort => return a new list
- list.sort! => sort the list in place
- Variable naming and their scope:
- begin with $ => global
- begin with @ => instance variable
- begin with @@ => class variable
- begin with [a-z_] => local
- begin with [A-Z] => constant
- Special global variables: $@, $_, $., ..., http://www.tutorialspoint.com/ruby/ruby_predefined_variables.htm
- Function arguments:
- variable length of arguments, (*args), then args will be a Enumerable
- default value def method(a=1, b)
- Operate on collection (Enumerable class): http://ruby-doc.org/core-2.0.0/Enumerable.html, mapping from Javascript Array methods:
- filter <=> select
- reduce <=> reduce, inject
- map <=> map, collect
- every <=> all?
- some <=> any?
- flat_map == collect_concat
- Lambda expression:
- function(x){return x*2;} => {|x| x*2}, do |x| x*2 end
- Ranges:
- (1..10) , double dot, includes 10
- (1...10), triple dot, does not include 10
- JSON like hash syntax works on later version of ruby. But the original syntax looks like:
- my_hash = { :a => 1, "b" => 2, 3 => 3 }
- Array decomposition can be used to pull out values from a array and assign them to variables:
- a, (b, *c), *d = 1, [2, 3, 4], 5, 6
- Support modifier form for if, unless, while, until
- a += 1 if a.zero?
- a += 1 while a < 10
- a += 1 until a > 10
- begin a+= 1 end while a < 10
- Ruby use `next` key word instead of `continue`
- Regex:
- create syntax => same as Javascript: /[0-9a-z]/i
- re.test( 'some string' ) <=> re === 'some string'
Total Pageviews
Friday, October 25, 2013
Ruby notes from Javascript coder
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment