ruby inbuilt function not working in a .rb file - ruby

I am unsure why my ruby code is not working, and any advice or help would be appreciated.
Could someone kindly advise me on how I can make this code work:
result = fetch_value.join(',').split(',').map(&:to_i)
I have the file below, named codeit.rb
# Function definitions first
def menu
# Clear the screen, and present the user with a menu
puts `clear`
puts "***Flatten an Array***"
puts "would you like to flatten an array?"
print "(y)yes, (n)no, (q)quit: "
gets.chomp.downcase
end
def flatten_array
print "great! lets do this! "
result = fetch_value.join(',').split(',').map(&:to_i)
puts "the answer is #{result}"
puts "press return to return to menu"
gets
end #end of flatten_array method
def fetch_value
puts "Please enter an array: "
gets.chomp
end
# run the app...
response = menu
while response != 'q'
case response
when 'y'
flatten_array
when 'n'
advanced_calc
end
response = menu
end
Running this code in the terminal, I get the following:
***Flatten an Array***
would you like to flatten an array?
(y)yes, (n)no, (q)quit: y
great! lets do this! Please enter an array:
[[1, 2, [3]], 4]
codeit.rb:14:in `flatten_array': undefined method `join' for "[[1, 2, [3]], 4]":String (NoMethodError)
from codeit.rb:35:in `<main>'
But when run similar commands in irb, the code seems to work:
2.3.0 :082 > array
=> [[1, 2, [3]], 4]
2.3.0 :083 >
2.3.0 :084 >
2.3.0 :085 >
2.3.0 :086 > array.join(',').split(',').map(&:to_i)
=> [1, 2, 3, 4]
2.3.0 :087 >

Your fetch_value method returns a string, not an array. And as the error says, the String class doesn't have a join method.
If you'd like to treat the string as an array -- essentially evaluating it as ruby code -- you could always use eval. Be aware that in any real code it's rather dangerous to use eval on a user-entered string, since your code will happily run whatever the user gives it.
With that caveat, you could do this:
def fetch_value
puts "Please enter an array: "
eval(gets.chomp)
end
You'll probably also need to consider what to do with the array. Currently, you're combining its elements into a string and then splitting that string back into an array, which doesn't make a lot of sense. And since your example also uses nested arrays, that join-and-split tango probably isn't doing what you think it is.

Related

How can I get different behaviour from class to_s method for string interpolation syntax?

I've written a class that is acting like an array for another class. I have a to_s method which returns in a similar manner to an array when used as follows:
array = [1, 2, 3, 4]
puts array
This results in the output:
1
2
3
4
When used with string interpolation puts "#{array}" the output is different:
[1, 2, 3, 4]
How can I implement a to_s method in my class to provide both a multiline output for when it is not used in string interpolation and a single line output when it is?
I considered trying to get the caller label with caller_locations(1,1)[0].label but this seems far from optimal. Any help or direction to the relevant documentation would be much appreciated, I haven't been able to find anything on the subject yet. Thanks!
Array#to_s does not (and should not) inspect the context it is called in. The array is printed differently, because puts checks if the given argument is an array (or can be converted to an array). From the documentation:
If called with an array argument, writes each element on a new line.
You can provide a to_ary method:
class MyArray
def to_s
[1, 2, 3].join('-')
end
def to_ary
[1, 2, 3]
end
end
a = MyArray.new
puts a # calls to_ary and then prints each item on a separate line
# 1
# 2
# 3
puts a.to_s # just prints the result of to_s
# 1-2-3
puts "#{a}" # same as above
# 1-2-3

Function calls in hash come up empty in Ruby

I've been sifting through the prior questions and answers on stackoverflow, and I have gotten most of my question figured out. I figured out that I can't place a function call within a hash, without placing it within a proc, or a similar container.
What I'm ultimately trying to do is have a menu displayed, grab user input, and then iterate through the hash, and run the specified function:
def Main()
menu_titles = {"Answer1" => Proc.new{Choice1()}}
Menu(menu_titles)
end
def Choice1()
puts "Response answer"
end
def Menu(menu_titles)
menu_titles.each_with_index do |(key, value),index|
puts "#{index+1}. #{key}"
end
user_input = 0
menu_titles.each_with_index do |(key, value), index|
if index.eql?(user_input)
menu_titles[value]
break
end
end
end
Main()
The issue I'm having right now is that I'm not entering the functions that my hash calls for. Whether I use a return or a "puts", I either get a blank line or nothing at all. If anyone has other recommendations about my code, I'm all ears also. To be honest, I don't like using procs, but that's mostly because I don't entirely know how they work and where to use them.
Right now for my menus I have:
user_input = 1
if user_input == 1
Choice1()
...
end
Here's how I would refactor this:
class Menu
attr_reader :titles
# initialize sets up a hard-coded titles instance variable,
# but it could easily take an argument.
def initialize
#titles = {
"Answer1" => Proc.new{ puts "choice 1" },
"Answer2" => Proc.new{ puts "choice 2" }
}
end
# This is the only public instance method in your class,
# which should give some idea about what the class is for
# to whoever reads your code
def choose
proc_for_index(display_for_choice)
end
private
# returns the index of the proc.
def display_for_choice
titles.each_with_index { |(key,value), index| puts "#{index + 1}. #{key}" }
gets.chomp.to_i - 1 # gets will return the string value of user input (try it in IRB)
end
# first finds the key for the selected index, then
# performs the hash lookup.
def proc_for_index(index)
titles[titles.keys[index]]
end
end
If you're serious about Ruby (or object-oriented programming in general), I would highly recommend learning about the advantages of packaging your code into behavior-specific classes. This example allows you to do this:
menu = Menu.new
proc = menu.choose
#=> 1. Answer1
#=> 2. Answer2
2 #(user input)
proc.call
#=> choice 2
And you could actually run it on one line:
Menu.new.choose.call

Ruby: how does one print a 2D array?

puts WINNING_ROWS.each{ |solution| "[ #{solution.map{ |space| "#{space}"}} ]"}
I tried doing the above, but it just lists each value with a new line char afterwards.
I'm trying to get the output:
[stuff,in,row,1]
[stuff,in,row,2]
etc
If this is just for debugging, the usual way is to say either
p expression
or
puts expression.inspect
...which is about the same thing.
You can also use pp.
require 'pp'
pp expression
pp(expr)
One could do something like this:
WINNING_ROWS = [[1,2,3],[4,5,6]]
WINNING_ROWS.map { |x| x.inspect }.join("")
Which will get you a string formatted as you requested
You're relying on the default to_s of Array. #each returns the array itself. So what you're doing is the same as puts WINNING_ROWS. Also, keep in mind that puts adds a newline at the end, so if you don't want that you have to use write (which is not available in the Kernel module like puts is, so you must call it directly on your STDOUT output).
You probably want something like:
WINNING_ROWS = [[1,2,3],[4,5,6]]
WINNING_ROWS.each {|row| STDOUT.write row.inspect }
=> [1, 2, 3][4, 5, 6]
# or this may work for you as well
# STDOUT.write WINNING_ROWS.inspect

Why do this Ruby object have both to_s and inspect methods that appear to do the same thing?

Why do this Ruby object both a to_s and inspect methods that appear to do the same thing?
The p method calls inspect and puts/print calls to_s for representing the object.
If I run
class Graph
def initialize
#nodeArray = Array.new
#wireArray = Array.new
end
def to_s # called with print / puts
"Graph : #{#nodeArray.size}"
end
def inspect # called with p
"G"
end
end
if __FILE__ == $0
gr = Graph.new
p gr
print gr
puts gr
end
I get
G
Graph : 0
Graph : 0
Then, why does Ruby have two functions do the same thing? What is the difference between to_s and inspect?
And what's the difference between puts, print, and p?
If I comment out the to_s or inspect function, I get as follows.
#<Graph:0x100124b88>
#<Graph:0x100124b88>
inspect is used more for debugging and to_s for end-user or display purposes.
For example, [1,2,3].to_s and [1,2,3].inspect produce different output.
inspect is a method that, by default, tells you the class name, the instance's object_id, and lists off the instance's instance variables.
print and puts are used, as you already know, to put the value of the object's to_s method to STDOUT. As indicated by Ruby's documentation, Object#to_s returns a string representing the object -- used for end-user readability.
print and puts are identical to each other except for puts automatically appends a newline, while print does not.
To compare with Python, to_s is like __str__ and inspect is like __repr__. to_s gives you a string, whereas inspect gives you the string representation of the object. You can use the latter to construct an object if you wish.
Further, there is a to_str method on certain objects, which you would call when you need a String-like object, and not just a string representation. (Try in IRB: [1,2,3].to_str and it will fail, yet [1,2,3].to_s will not.) I feel I should mention this because I've been bitten by it before :)
For anyone arriving here after starting out with Ruby Koans, a simple example of where to_s and inspect differ in output is this:
nil.to_s # will yield an empty string, ie ""
nil.inspect # will yield the string "nil"
puts generally prints the result of applying to_s on an object, while p prints the result of inspecting the object.
There is a subtle difference between inspect and to_s:
inspect, when applied on an object, returns the object hex code
along with the instance variable
to_s, when applied on an object,returns only the object hex code
class Item
def initialize(abc)
#abc=abc
end
end
x= Item.new(22)
puts x #prints object x hex code
puts x.inspect #prints object x hex code WITH INSTANCE VARIABLE #abc
puts x.to_s #prints object x hex code
p x #prints object x hex code WITH INSTANCE VARIABLE #abc
p x.inspect #prints object x hex code WITH INSTANCE VARIABLE #abc
p x.to_s #prints object x hex code
Answer from Chris Pine's Learn To Program book
"The inspect method is a lot like to_s, except that the string it returns tries to show you the ruby code for building the object you passed it."
Thus the inspect method will return an array for example like this...
[25, 16, 9, 4, 1, 0]
Where as puts / to_s will return
25
16
9
4
1
0
2.0.0p195 :075 > puts (1..5).to_a # Put an array as a string.
1
2
3
4
5
=> nil
2.0.0p195 :076 > puts (1..5).to_a.inspect # Put a literal array.
[1, 2, 3, 4, 5]
=> nil
2.0.0p195 :077 > puts :name, :name.inspect
name
:name
=> nil
2.0.0p195 :078 > puts "It worked!", "It worked!".inspect
It worked!
"It worked!"
=> nil
2.0.0p195 :079 > p :name # Same as 'puts :name.inspect'
:name
=> :name
From the Rails Tutorial
Refer following link for more information and examples explaining difference between "to_s" and "inspect" as well as difference between "puts" and "p".
https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/108-displaying-objects

Hidden features of Ruby

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.
Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.
See also:
Hidden features of C#
Hidden features of Java
Hidden features of JavaScript
Hidden features of Ruby on Rails
Hidden features of Python
(Please, just one hidden feature per answer.)
Thank you
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
Peter Cooper has a good list of Ruby tricks. Perhaps my favorite of his is allowing both single items and collections to be enumerated. (That is, treat a non-collection object as a collection containing just that object.) It looks like this:
[*items].each do |item|
# ...
end
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"}
One trick I like is to use the splat (*) expander on objects other than Arrays. Here's an example on a regular expression match:
match, text, number = *"Something 981".match(/([A-z]*) ([0-9]*)/)
Other examples include:
a, b, c = *('A'..'Z')
Job = Struct.new(:name, :occupation)
tom = Job.new("Tom", "Developer")
name, occupation = *tom
Wow, no one mentioned the flip flop operator:
1.upto(100) do |i|
puts i if (i == 3)..(i == 15)
end
One of the cool things about ruby is that you can call methods and run code in places other languages would frown upon, such as in method or class definitions.
For instance, to create a class that has an unknown superclass until run time, i.e. is random, you could do the following:
class RandomSubclass < [Array, Hash, String, Fixnum, Float, TrueClass].sample
end
RandomSubclass.superclass # could output one of 6 different classes.
This uses the 1.9 Array#sample method (in 1.8.7-only, see Array#choice), and the example is pretty contrived but you can see the power here.
Another cool example is the ability to put default parameter values that are non fixed (like other languages often demand):
def do_something_at(something, at = Time.now)
# ...
end
Of course the problem with the first example is that it is evaluated at definition time, not call time. So, once a superclass has been chosen, it stays that superclass for the remainder of the program.
However, in the second example, each time you call do_something_at, the at variable will be the time that the method was called (well, very very close to it)
Another tiny feature - convert a Fixnum into any base up to 36:
>> 1234567890.to_s(2)
=> "1001001100101100000001011010010"
>> 1234567890.to_s(8)
=> "11145401322"
>> 1234567890.to_s(16)
=> "499602d2"
>> 1234567890.to_s(24)
=> "6b1230i"
>> 1234567890.to_s(36)
=> "kf12oi"
And as Huw Walters has commented, converting the other way is just as simple:
>> "kf12oi".to_i(36)
=> 1234567890
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.
Another fun addition in 1.9 Proc functionality is Proc#curry which allows you to turn a Proc accepting n arguments into one accepting n-1. Here it is combined with the Proc#=== tip I mentioned above:
it_is_day_of_week = lambda{ |day_of_week, date| date.wday == day_of_week }
it_is_saturday = it_is_day_of_week.curry[6]
it_is_sunday = it_is_day_of_week.curry[0]
case Time.now
when it_is_saturday
puts "Saturday!"
when it_is_sunday
puts "Sunday!"
else
puts "Not the weekend"
end
Download Ruby 1.9 source, and issue make golf, then you can do things like this:
make golf
./goruby -e 'h'
# => Hello, world!
./goruby -e 'p St'
# => StandardError
./goruby -e 'p 1.tf'
# => 1.0
./goruby19 -e 'p Fil.exp(".")'
"/home/manveru/pkgbuilds/ruby-svn/src/trunk"
Read the golf_prelude.c for more neat things hiding away.
Boolean operators on non boolean values.
&& and ||
Both return the value of the last expression evaluated.
Which is why the ||= will update the variable with the value returned expression on the right side if the variable is undefined. This is not explicitly documented, but common knowledge.
However the &&= isn't quite so widely known about.
string &&= string + "suffix"
is equivalent to
if string
string = string + "suffix"
end
It's very handy for destructive operations that should not proceed if the variable is undefined.
The Symbol#to_proc function that Rails provides is really cool.
Instead of
Employee.collect { |emp| emp.name }
You can write:
Employee.collect(&:name)
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'
}
Use a Range object as an infinite lazy list:
Inf = 1.0 / 0
(1..Inf).take(5) #=> [1, 2, 3, 4, 5]
More info here: http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/
I find using the define_method command to dynamically generate methods to be quite interesting and not as well known. For example:
((0..9).each do |n|
define_method "press_#{n}" do
#number = #number.to_i * 10 + n
end
end
The above code uses the 'define_method' command to dynamically create the methods "press1" through "press9." Rather then typing all 10 methods which essentailly contain the same code, the define method command is used to generate these methods on the fly as needed.
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!'
Short inject, like such:
Sum of range:
(1..10).inject(:+)
=> 55
Warning: this item was voted #1 Most Horrendous Hack of 2008, so use with care. Actually, avoid it like the plague, but it is most certainly Hidden Ruby.
Superators Add New Operators to Ruby
Ever want a super-secret handshake operator for some unique operation in your code? Like playing code golf? Try operators like
-~+~-
or
<---
That last one is used in the examples for reversing the order of an item.
I have nothing to do with the Superators Project beyond admiring it.
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?)
Auto-vivifying hashes in Ruby
def cnh # silly name "create nested hash"
Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}
end
my_hash = cnh
my_hash[1][2][3] = 4
my_hash # => { 1 => { 2 => { 3 =>4 } } }
This can just be damn handy.
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.
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.
create an array of consecutive numbers:
x = [*0..5]
sets x to [0, 1, 2, 3, 4, 5]
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".
use anything that responds to ===(obj) for case comparisons:
case foo
when /baz/
do_something_with_the_string_matching_baz
when 12..15
do_something_with_the_integer_between_12_and_15
when lambda { |x| x % 5 == 0 }
# only works in Ruby 1.9 or if you alias Proc#call as Proc#===
do_something_with_the_integer_that_is_a_multiple_of_5
when Bar
do_something_with_the_instance_of_Bar
when some_object
do_something_with_the_thing_that_matches_some_object
end
Module (and thus Class), Regexp, Date, and many other classes define an instance method :===(other), and can all be used.
Thanks to Farrel for the reminder of Proc#call being aliased as Proc#=== in Ruby 1.9.
The "ruby" binary (at least MRI's) supports a lot of the switches that made perl one-liners quite popular.
Significant ones:
-n Sets up an outer loop with just "gets" - which magically works with given filename or STDIN, setting each read line in $_
-p Similar to -n but with an automatic puts at the end of each loop iteration
-a Automatic call to .split on each input line, stored in $F
-i In-place edit input files
-l Automatic call to .chomp on input
-e Execute a piece of code
-c Check source code
-w With warnings
Some examples:
# Print each line with its number:
ruby -ne 'print($., ": ", $_)' < /etc/irbrc
# Print each line reversed:
ruby -lne 'puts $_.reverse' < /etc/irbrc
# Print the second column from an input CSV (dumb - no balanced quote support etc):
ruby -F, -ane 'puts $F[1]' < /etc/irbrc
# Print lines that contain "eat"
ruby -ne 'puts $_ if /eat/i' < /etc/irbrc
# Same as above:
ruby -pe 'next unless /eat/i' < /etc/irbrc
# Pass-through (like cat, but with possible line-end munging):
ruby -p -e '' < /etc/irbrc
# Uppercase all input:
ruby -p -e '$_.upcase!' < /etc/irbrc
# Same as above, but actually write to the input file, and make a backup first with extension .bak - Notice that inplace edit REQUIRES input files, not an input STDIN:
ruby -i.bak -p -e '$_.upcase!' /etc/irbrc
Feel free to google "ruby one-liners" and "perl one-liners" for tons more usable and practical examples. It essentially allows you to use ruby as a fairly powerful replacement to awk and sed.
The send() method is a general-purpose method that can be used on any Class or Object in Ruby. If not overridden, send() accepts a string and calls the name of the method whose string it is passed. For example, if the user clicks the “Clr” button, the ‘press_clear’ string will be sent to the send() method and the ‘press_clear’ method will be called. The send() method allows for a fun and dynamic way to call functions in Ruby.
%w(7 8 9 / 4 5 6 * 1 2 3 - 0 Clr = +).each do |btn|
button btn, :width => 46, :height => 46 do
method = case btn
when /[0-9]/: 'press_'+btn
when 'Clr': 'press_clear'
when '=': 'press_equals'
when '+': 'press_add'
when '-': 'press_sub'
when '*': 'press_times'
when '/': 'press_div'
end
number.send(method)
number_field.replace strong(number)
end
end
I talk more about this feature in Blogging Shoes: The Simple-Calc Application
Fool some class or module telling it has required something that it really hasn't required:
$" << "something"
This is useful for example when requiring A that in turns requires B but we don't need B in our code (and A won't use it either through our code):
For example, Backgroundrb's bdrb_test_helper requires 'test/spec', but you don't use it at all, so in your code:
$" << "test/spec"
require File.join(File.dirname(__FILE__) + "/../bdrb_test_helper")
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.
private unless Rails.env == 'test'
# e.g. a bundle of methods you want to test directly
Looks like a cool and (in some cases) nice/useful hack/feature of Ruby.

Resources