Examples of methods with single string arguments - ruby

Could someone give me an example of a method that accepts a single string argument. Whilst i appreciate this might seem trivial I am trying to understand how this works in ruby. Would the syntax below be correct.
Def method("argument")
true
end

You need to check if it is a string by yourself. You can make use of is_a? to see if it is a String as Ruby is dynamically typed.
def add_watson(f_name)
f_name << " Watson" if f_name.is_a? String
end
Now, calling it
puts add_watson("Emma") #=> Emma Watson

No, it wouldn't. First of all, def keyword is lowercased. Also, method argument(s) is written like this def my_method(argument) and at this point it doesn't check if it's string, in fact, it can accept any object, because Ruby is typed dynamically. If you want to force String instance as an argument, you can do it inside of method body:
def my_method(argument)
raise ArgumentError, "argument must be a String" unless argument.is_a? String
true
end

Your syntax is wrong.
def method(arg)
puts "arg"
end
You can review some tutorial too
http://www.tutorialspoint.com/ruby/ruby_methods.htm
http://www.skorks.com/2009/08/method-arguments-in-ruby/

Related

Ruby default block and yield

I am working on the following problem:
describe "some silly block functions" do
describe "reverser" do
it "reverses the string returned by the default block" do
result = reverser do
"hello"
end
expect(result).to eq("olleh")
end
From my understanding this should reverse a string. My code is as follows:
def reverser
yield "hello"
end
reverser do |i|
puts i.reverse
end
This simply returns "hello". I may be missing some fundamental concepts here about how yield, blocks, and functions all interact. How do I going about doing what I am trying to accomplish?
The answers are good and correct but perhaps it still do not help.
You should start with your spec:
it "reverses the string returned by the default block"
So, it's very clear what your method should do:
def reverser
# should reverse the string returned by the default block
end
Let's now see how to achieve it. Ok, it should reverse something. But what? Let's see:
string returned by the default block
This suggests that we need to execute the default block and get its returned value. Let's see what the docs say:
yield - Called from inside a method body, yields control to the code block (if any) supplied as part of the method call. ... The value of a call to yield is the value of the executed code block.
So, it seems that your method needs to perform a yield. It will execute a block and return the value the block returns. So, just put a yield there.
def reverser
yield
end
If you run your spec, it will complain - you will see that the string is still not reversed. So, that's whats left for your method to do:
def reverser
yield.reverse
end
and that's it.
You need to include the logic of reversing the string in reverser.
def reverser
yield.reverse
end
But why bothering using block anyway? It's much clearer to use a normal parameter.
def reverser(str)
str.reverse
end
reverser('hello') #=> olleh
If you want to put the string to reverse in the block, then you need to get the result of calling the block and reverse it.
def reverser(&block)
block.call.reverse
end
irb(main):009:0> result = reverser do
irb(main):010:1* "hello"
irb(main):011:1> end
=> "olleh"
I know it's been a year but this hasn't been answered right.
def reverser
out = []
yield.split.each{|word| out << word.reverse}
out.join(" ")
end
I'm pretty sure it has to do with scope
I agree with the above responses - they make the most sense. but want to add why your code isn't working and how to fix it:
expect(result).to eq("olleh")
So according to that you want result to return a string. Is it doing that?
puts returns nil. when you have puts at the end of a method - be aware that the method will return nil. It's insidious because sometimes the results are not what is expected.
but you are expecting it to return 'olleh'
get rid of the puts and it should work like you expect (untested)
def reverser
yield "hello"
end
reverser do |i|
i.reverse # NOTE THAT THE PUTS is missing here
end
I think that's what you are looking for.
edit: Please test and let me know because some folks think I have the answer completely wrong! of course you'd not want to rely on the particular block that you are using as a design point, but this should give you an idea of why it wasn't working

Handing regex string to method

Within a method, I want to dynamically evaluate the following code chunk with a regex:
if (/^[A-F][A-Z]*[^\.\*]$/).match(some_value)
The method I attempted is this:
def check(val)
if (/^[val][A-Z]*[^\.\*]$/).match(some_value)
puts "foo"
else
puts "waa"
end
end
check("A-F")
The value I am passing in is not making it there correctly. It appears that passing a value in this fashion needs something more. Is this not something you can do with a method?
You expected string interpolation. To do that, you need to use the interpolation syntax #{}:
def check(val)
if (/^[#{val}][A-Z]*[^\.\*]$/).match(some_value)
puts "foo"
else
puts "waa"
end
end

How to make sure method have certain type in ruby

As you probably know, ruby, like most scripting languages is dynamically-typed. How can I make sure parameter passed to my method is instance of specific class?
Check its type.
That said, why? In general you should be caring about its duckitude, not its type. I'm generally suspicious when something is tied to its type rather than its messages.
Use is_a?:
def your_method(param)
if param.is_a? String
# it's a string
else
# not a string
end
end
Or, if you have lots of classes to check, a case statement:
def your_method(param)
case param
when String
# it's a string
when Array
# it's an array
when Rational
# it's a rational
# ...
else
# it's not any of these classes
end
end
It is up to caller to provide the argument of correct type. It is common in Ruby to raise ArgumentError if the method is called with an argument of unsupported type. Example:
def do_something_with_a_number(number)
raise ArgumentError, "you have to provide a number" unless number.is_a?(Fixnum)
...
end

Can I tell a Ruby method to expect a specific parameter type?

def doSomething(value)
if (value.is_a?(Integer))
print value * 2
else
print "Error: Expected integer value"
exit
end
end
Can I tell a Ruby method that a certain parameter should be an Integer, otherwise crash? Like Java.
No, you can't. You can only do what you're already doing: check the type yourself.
I'm late to the party, but I wanted to add something else:
A really important concept in Ruby is Duck Typing. The idea behind this principle is that you don't really care about the types of your variables, as far as they can do what you want to do with them. What you want in your method is to accept a variable that responds to (*). You don't care about the class name as far as the instance can be multiplied.
Because of that, in Ruby you will see more often the method #responds_to? than #is_a?
In general, you will be doing type assertion only when accepting values from external sources, such as user input.
I would suggest a raise unless type match at the beginning of the method
def do_something(value)
raise TypeError, 'do_something expects an integer' unless value.kind_of?(Integer)
...
end
This is raise an error and exit unless value is an Integer
You can raise an Exception anytime arbitrarily if you deem it necessary.
def doSomething(value)
if (value.is_a?(Integer))
print value * 2
else
raise "Expected integer value"
end
end
Whether or not you really want to do this is a separate issue. :)
Ruby doesn't have parameter type verification, though you can add sugar method to all objects for convenience to verify type like this:
def doSomething(value)
print value.should_be(Numeric) * 2
end
or
def initialize(fruit)
#fruit = fruit.should_be(Fruit)
end
Object.class_eval do
def should_be cls
hide_from_stack = true
if self && !self.is_a?(cls)
raise("Expected class #{cls}, got #{self.class}")
end
self
end
end

What does question mark mean in the definition of function in ruby?

I have got a function like this--
Function's name is seld.is_dl and it is accepting path parameter. My question is that what does this ? sign in the function definition indicate.
def self.is_dl?(path)
path = File.basename(path)
if path =~ /setup.exe/i
return false
else
return true
end
end
I am java developer and I have seen "?" in case of If-ELSE block mainly, that is why I am not able to figure what does this mean?
? is a valid character in a method name.
It is typically used to denote a method that returns true or false
For example:
File.exists?
File.readable?
String#ascii_only?
etc
Note: ! is also a valid character. It is typically used to denote a "destructive" method
String#capitalize!
String#downcase!
String#rstrip!
etc
If you're feeling like going the extra mile, Ruby technically allows any string to be a method name. Odd ones need define_method() and send() calls, but formally there’s no restriction.
module Hello
class << self
define_method "this is my method :)" do |foo|
puts "you gave my method #{foo}"
end
define_method "this isn't your method :(, sorry" do
puts "sorry, not your method, bro"
end
end
end
Hello.send("this is my method :)", "candy")
#=> you gave my method candy
Hello.send("this isn't your method :(, sorry")
#=> sorry, not your method, bro

Resources