Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 316 Vote(s) - 3.34 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Hidden features of Ruby

#31
**Destructuring an Array**

(a, b), c, d = [ [:a, :b ], :c, [:d1, :d2] ]

Where:

a #=> :a
b #=> :b
c #=> :c
d #=> [:d1, :d2]

Using this technique we can use simple assignment to get the exact values we want out of nested array of any depth.
Reply

#32
I'm a fan of:

%w{An Array of strings} #=> ["An", "Array", "of", "Strings"]

It's sort of funny how often that's useful.
Reply

#33
**Defining a method that accepts any number of parameters and just discards them all**

def hello(*)
super
puts "hello!"
end

The above `hello` method only needs to `puts` `"hello"` on the screen and call `super` - but since the superclass `hello` defines parameters it has to as well - however since it doesn't actually need to use the parameters itself - it doesn't have to give them a name.
Reply

#34
How about opening a file based on ARGV[0]?

`readfile.rb:`

$<.each_line{|l| puts l}

ruby readfile.rb testfile.txt

It's a great shortcut for writing one-off scripts. There's a whole mess of pre-defined variables that most people don't know about. Use them wisely (read: don't litter a code base you plan to maintain with them, it can get messy).
Reply

#35
I just *love* the inline keyword **rescue** like this:
**EDITED EXAMPLE:**

@user #=> nil (but I did't know)
@user.name rescue "Unknown"
link_to( d.user.name, url_user( d.user.id, d.user.name)) rescue 'Account removed'


This avoid breaking my App and is way better than the feature released at Rails *.try()*
Reply

#36
Calling a method defined anywhere in the inheritance chain, even if overridden

ActiveSupport's objects sometimes masquerade as built-in objects.

<pre>
require 'active_support'
days = 5.days
days.class #=> Fixnum
days.is_a?(Fixnum) #=> true
Fixnum === days #=> false (huh? what are you really?)
Object.instance_method(:class).bind(days).call #=> ActiveSupport::Duration (aha!)
ActiveSupport::Duration === days #=> true
</pre>

The above, of course, relies on the fact that active_support doesn't redefine Object#instance_method, in which case we'd really be up a creek. Then again, we could always save the return value of Object.instance_method(:class) before any 3rd party library is loaded.

Object.instance_method(...) returns an UnboundMethod which you can then bind to an instance of that class. In this case, you can bind it to any instance of Object (subclasses included).

If an object's class includes modules, you can also use the UnboundMethod from those modules.

<pre>
module Mod
def var_add(more); @var+more; end
end
class Cla
include Mod
def initialize(var); @var=var; end
# override
def var_add(more); @var+more+more; end
end
cla = Cla.new('abcdef')
cla.var_add('ghi') #=> "abcdefghighi"
Mod.instance_method(:var_add).bind(cla).call('ghi') #=> "abcdefghi"
</pre>

This even works for singleton methods that override an instance method of the class the object belongs to.
<pre>
class Foo
def mymethod; 'original'; end
end
foo = Foo.new
foo.mymethod #=> 'original'
def foo.mymethod; 'singleton'; end
foo.mymethod #=> 'singleton'
Foo.instance_method(:mymethod).bind(foo).call #=> 'original'

# You can also call #instance method on singleton classes:
class << foo; self; end.instance_method(:mymethod).bind(foo).call #=> 'singleton'
</pre>
Reply

#37
Multiple return values
----------------------

def getCostAndMpg
cost = 30000 # some fancy db calls go here
mpg = 30
return cost,mpg
end
AltimaCost, AltimaMpg = getCostAndMpg
puts "AltimaCost = #{AltimaCost}, AltimaMpg = #{AltimaMpg}"




Parallel Assignment
-------------------

i = 0
j = 1
puts "i = #{i}, j=#{j}"
i,j = j,i
puts "i = #{i}, j=#{j}"




Virtual Attributes
------------------

class Employee < Person
def initialize(fname, lname, position)
super(fname,lname)
@position = position
end
def to_s
super + ", #@position"
end
attr_writer :position
def etype
if @position == "CEO" || @position == "CFO"
"executive"
else
"staff"
end
end
end
employee = Employee.new("Augustus","Bondi","CFO")
employee.position = "CEO"
puts employee.etype => executive
employee.position = "Engineer"
puts employee.etype => staff




method_missing - a wonderful idea
---------------------------------
*(In most languages when a method cannot be found and error is thrown and your program stops. In ruby you can actually catch those errors and perhaps do something intelligent with the situation)*

class MathWiz
def add(a,b)
return a+b
end
def method_missing(name, *args)
puts "I don't know the method #{name}"
end
end
mathwiz = MathWiz.new
puts mathwiz.add(1,4)
puts mathwiz.subtract(4,2)

> 5
>
> I don't know the method subtract
>
> nil




Reply

#38
From Ruby 1.9 Proc#=== is an alias to Proc#call, which means Proc objects can be used in case statements like so:

def multiple_of(factor)
Proc.new{|product| product.modulo(factor).zero?}
end

case number
when multiple_of(3)
puts "Multiple of 3"
when multiple_of(7)
puts "Multiple of 7"
end
Reply

#39
A lot of the magic you see in Rubyland has to do with metaprogramming, which is simply writing code that writes code for you. Ruby's `attr_accessor`, `attr_reader`, and `attr_writer` are all simple metaprogramming, in that they create two methods in one line, following a standard pattern. Rails does a whole lot of metaprogramming with their relationship-management methods like `has_one` and `belongs_to`.

But it's pretty simple to create your own metaprogramming tricks using `class_eval` to execute dynamically-written code.

The following example allows a wrapper object to forwards certain methods along to an internal object:

class Wrapper
attr_accessor :internal

def self.forwards(*methods)
methods.each do |method|
define_method method do |*arguments, &block|
internal.send method, *arguments, &block
end
end
end

forwards :to_i, :length, :split
end

w = Wrapper.new
w.internal = "12 13 14"
w.to_i # => 12
w.length # => 8
w.split('1') # => ["", "2 ", "3 ", "4"]

The method `Wrapper.forwards` takes symbols for the names of methods and stores them in the `methods` array. Then, for each of those given, we use `define_method` to create a new method whose job it is to send the message along, including all arguments and blocks.

A great resource for metaprogramming issues is [Why the Lucky Stiff's "Seeing Metaprogramming Clearly"][1].

[1]:

[To see links please register here]

Reply

#40
There are some aspects of symbol literals that people should know. One case solved by special symbol literals is when you need to create a symbol whose name causes a syntax error for some reason with the normal symbol literal syntax:

:'class'

You can also do symbol interpolation. In the context of an accessor, for example:

define_method :"#{name}=" do |value|
instance_variable_set :"@#{name}", value
end
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through