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

#11
Don't know how hidden this is, but I've found it useful when needing to make a Hash out of a one-dimensional array:

fruit = ["apple","red","banana","yellow"]
=> ["apple", "red", "banana", "yellow"]

Hash[*fruit]
=> {"apple"=>"red", "banana"=>"yellow"}


Reply

#12
One final one - in ruby you can use any character you want to delimit strings. Take the following code:

message = "My message"
contrived_example = "<div id=\"contrived\">#{message}</div>"

If you don't want to escape the double-quotes within the string, you can simply use a different delimiter:

contrived_example = %{<div id="contrived-example">#{message}</div>}
contrived_example = %[<div id="contrived-example">#{message}</div>]

As well as avoiding having to escape delimiters, you can use these delimiters for nicer multiline strings:

sql = %{
SELECT strings
FROM complicated_table
WHERE complicated_condition = '1'
}

Reply

#13
# module_function
Module methods that are declared as *module_function* will create copies of themselves as **private** instance methods in the class that includes the Module:

module M
def not!
'not!'
end
module_function :not!
end

class C
include M

def fun
not!
end
end

M.not! # => 'not!
C.new.fun # => 'not!'
C.new.not! # => NoMethodError: private method `not!' called for #<C:0x1261a00>

If you use *module_function* without any arguments, then any module methods that comes after the module_function statement will automatically become module_functions themselves.


module M
module_function

def not!
'not!'
end

def yea!
'yea!'
end
end


class C
include M

def fun
not! + ' ' + yea!
end
end
M.not! # => 'not!'
M.yea! # => 'yea!'
C.new.fun # => 'not! yea!'
Reply

#14
`Class.new()`

Create a new class at run time. The argument can be a class to derive from, and the block is the class body. You might also want to look at `const_set/const_get/const_defined?` to get your new class properly registered, so that `inspect` prints out a name instead of a number.

Not something you need every day, but quite handy when you do.
Reply

#15
Ruby has a [call/cc][1] mechanism allowing one to freely hop up and down the stack.

Simple example follows. This is certainly not how one would multiply a sequence in ruby, but it demonstrates how one might use call/cc to reach up the stack to short-circuit an algorithm. In this case, we're recursively multiplying a list of numbers until we either have seen every number or we see zero (the two cases where we know the answer). In the zero case, we can be arbitrarily deep in the list and terminate.

#!/usr/bin/env ruby

def rprod(k, rv, current, *nums)
puts "#{rv} * #{current}"
k.call(0) if current == 0 || rv == 0
nums.empty? ? (rv * current) : rprod(k, rv * current, *nums)
end

def prod(first, *rest)
callcc { |k| rprod(k, first, *rest) }
end

puts "Seq 1: #{prod(1, 2, 3, 4, 5, 6)}"
puts ""
puts "Seq 2: #{prod(1, 2, 0, 3, 4, 5, 6)}"

You can see the output here:

[

[To see links please register here]

][2]

For a more complex example featuring continuations moving the other direction on the stack, read the source to [Generator][3].


[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

Reply

#16
Short inject, like such:

[Sum of range:][1]

(1..10).inject(:+)
=> 55


[1]:

[To see links please register here]

Reply

#17
Hashes with default values! An array in this case.

parties = Hash.new {|hash, key| hash[key] = [] }
parties["Summer party"]
# => []

parties["Summer party"] << "Joe"
parties["Other party"] << "Jane"

Very useful in metaprogramming.
Reply

#18
I find this useful in some scripts. It makes it possible to use environment variables directly, like in shell scripts and Makefiles. Environment variables are used as fall-back for undefined Ruby constants.

>> class <<Object
>> alias :old_const_missing :const_missing
>> def const_missing(sym)
>> ENV[sym.to_s] || old_const_missing(sym)
>> end
>> end
=> nil

>> puts SHELL
/bin/zsh
=> nil
>> TERM == 'xterm'
=> true
Reply

#19
create an array of consecutive numbers:

x = [*0..5]

sets x to [0, 1, 2, 3, 4, 5]

Reply

#20
I'm late to the party, but:

You can easily take two equal-length arrays and turn them into a hash with one array supplying the keys and the other the values:

a = [:x, :y, :z]
b = [123, 456, 789]

Hash[a.zip(b)]
# => { :x => 123, :y => 456, :z => 789 }

(This works because Array#zip "zips" up the values from the two arrays:

a.zip(b) # => [[:x, 123], [:y, 456], [:z, 789]]

And Hash[] can take just such an array. I've seen people do this as well:

Hash[*a.zip(b).flatten] # unnecessary!

Which yields the same result, but the splat and flatten are wholly unnecessary--perhaps they weren't in the past?)
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

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